home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / tex / webtp55.zip / WEAVE.WEB (.txt) < prev    next >
Texinfo Document  |  1989-11-02  |  190KB  |  4,209 lines

  1. % This program by D. E. Knuth is not copyrighted and can be used freely.
  2. % Version 0 was released in December, 1981.
  3. % Version 1 was released in September, 1982, with version 0 of TeX.
  4. % Slight changes were made in October, 1982, for version 0.6 of TeX.
  5. % Version 1.1 changed "_" to "\_" if not within an identifier (November, 1982).
  6. % Version 1.2 added @@= and @@\ and marked changed modules (December, 1982).
  7. % Version 1.3 marked and indexed changed modules better (January, 1983).
  8. % Version 1.4 added "history" (February, 1983).
  9. % Version 1.5 conformed to TeX version 0.96 (March, 1983).
  10. % Version 1.6 conformed to TeX version 0.98 (May, 1983).
  11. % Version 1.7 introduced the new change file format (June, 1983).
  12. % Version 2 was released in July, 1983, with version 0.999 of TeX.
  13. % Version 2.1 corrected a bug in changed_module reckoning (August, 1983).
  14. % Version 2.2 corrected it better (August, 1983).
  15. % Version 2.3 starts the output with \input webmac (August, 1983).
  16. % Version 2.4 fixed a bug in compress(#) (September, 1983).
  17. % Version 2.5 cleared xrefswitch after module names (November, 1983).
  18. % Version 2.6 fixed a bug in declaration of trans array (January, 1984).
  19. % Version 2.7 fixed a bug in real constants (August, 1984).
  20. % Version 2.8 fixed a bug in change_buffer movement (August, 1985).
  21. % Version 2.9 increased max_refs and max_toks to 30000 each (January, 1987).
  22. % Version 3, for Sewell's book, fixed a long-line bug in input_ln (March, 1989).
  23. % Version 3.1 fixed a bug for programs with only one module (April, 1989).
  24. % Version 4 was major change to allow 8-bit input (September, 1989).
  25. % Here is TeX material that gets inserted after \input webmac
  26. \def\hang{\hangindent 3em\indent\ignorespaces}
  27. \font\ninerm=cmr9
  28. \let\mc=\ninerm % medium caps for names like SAIL
  29. \def\PASCAL{Pascal}
  30. \def\pb{$\.|\ldots\.|$} % Pascal brackets (|...|)
  31. \def\v{\.{\char'174}} % vertical (|) in typewriter font
  32. \def\dleft{[\![} \def\dright{]\!]} % double brackets
  33. \mathchardef\RA="3221 % right arrow
  34. \mathchardef\BA="3224 % double arrow
  35. \def\({} % kludge for alphabetizing certain module names
  36. \def\title{WEAVE}
  37. \def\contentspagenumber{15} % should be odd
  38. \def\topofcontents{\null\vfill
  39.   \titlefalse % include headline on the contents page
  40.   \def\rheader{\mainfont Appendix D\hfil \contentspagenumber}
  41.   \centerline{\titlefont The {\ttitlefont WEAVE} processor}
  42.   \vskip 15pt
  43.   \centerline{(Version 4)}
  44.   \vfill}
  45. \pageno=\contentspagenumber \advance\pageno by 1
  46. @* Introduction.
  47. This program converts a \.{WEB} file to a \TeX\ file. It was written
  48. by D. E. Knuth in October, 1981; a somewhat similar {\mc SAIL} program had
  49. been developed in March, 1979, although the earlier program used a top-down
  50. parsing method that is quite different from the present scheme.
  51. The code uses a few features of the local \PASCAL\ compiler that may need
  52. to be changed in other installations:
  53. \yskip\item{1)} Case statements have a default.
  54. \item{2)} Input-output routines may need to be adapted for use with a particular
  55. character set and/or for printing messages on the user's terminal.
  56. \yskip\noindent
  57. These features are also present in the \PASCAL\ version of \TeX, where they
  58. are used in a similar (but more complex) way. System-dependent portions
  59. of \.{WEAVE} can be identified by looking at the entries for `system
  60. dependencies' in the index below.
  61. @!@^system dependencies@>
  62. The ``banner line'' defined here should be changed whenever \.{WEAVE}
  63. is modified.
  64. @d banner=='This is WEAVE, Version 4'
  65. @ The program begins with a fairly normal header, made up of pieces that
  66. @^system dependencies@>
  67. will mostly be filled in later. The \.{WEB} input comes from files |web_file|
  68. and |change_file|, and the \TeX\ output goes to file |tex_file|.
  69. If it is necessary to abort the job because of a fatal error, the program
  70. calls the `|jump_out|' procedure, which goes to the label |end_of_WEAVE|.
  71. @d end_of_WEAVE = 9999 {go here to wrap it up}
  72. @p @t\4@>@<Compiler directives@>@/
  73. program WEAVE(@!web_file,@!change_file,@!tex_file);
  74. label end_of_WEAVE; {go here to finish}
  75. const @<Constants in the outer block@>@/
  76. type @<Types in the outer block@>@/
  77. var @<Globals in the outer block@>@/
  78. @<Error handling procedures@>@/
  79. procedure initialize;
  80.   var @<Local variables for initialization@>@/
  81.   begin @<Set initial values@>@/
  82.   end;
  83. @ Some of this code is optional for use when debugging only;
  84. such material is enclosed between the delimiters |debug| and $|gubed|$.
  85. Other parts, delimited by |stat| and $|tats|$, are optionally included
  86. if statistics about \.{WEAVE}'s memory usage are desired.
  87. @d debug==@{ {change this to `$\\{debug}\equiv\null$' when debugging}
  88. @d gubed==@t@>@} {change this to `$\\{gubed}\equiv\null$' when debugging}
  89. @f debug==begin
  90. @f gubed==end
  91. @d stat==@{ {change this to `$\\{stat}\equiv\null$'
  92.   when gathering usage statistics}
  93. @d tats==@t@>@} {change this to `$\\{tats}\equiv\null$'
  94.   when gathering usage statistics}
  95. @f stat==begin
  96. @f tats==end
  97. @ The \PASCAL\ compiler used to develop this system has ``compiler
  98. directives'' that can appear in comments whose first character is a dollar sign.
  99. In production versions of \.{WEAVE} these directives tell the compiler that
  100. @^system dependencies@>
  101. it is safe to avoid range checks and to leave out the extra code it inserts
  102. for the \PASCAL\ debugger's benefit, although interrupts will occur if
  103. there is arithmetic overflow.
  104. @<Compiler directives@>=
  105. @{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
  106. @!debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}
  107. @ Labels are given symbolic names by the following definitions. We insert
  108. the label `|exit|:' just before the `\ignorespaces|end|\unskip' of a
  109. procedure in which we have used the `|return|' statement defined below;
  110. the label `|restart|' is occasionally used at the very beginning of a
  111. procedure; and the label `|reswitch|' is occasionally used just prior to
  112. a \&{case} statement in which some cases change the conditions and we wish to
  113. branch to the newly applicable case.
  114. Loops that are set up with the \&{loop} construction defined below are
  115. commonly exited by going to `|done|' or to `|found|' or to `|not_found|',
  116. and they are sometimes repeated by going to `|continue|'.
  117. @d exit=10 {go here to leave a procedure}
  118. @d restart=20 {go here to start a procedure again}
  119. @d reswitch=21 {go here to start a case statement again}
  120. @d continue=22 {go here to resume a loop}
  121. @d done=30 {go here to exit a loop}
  122. @d found=31 {go here when you've found it}
  123. @d not_found=32 {go here when you've found something else}
  124. @ Here are some macros for common programming idioms.
  125. @d incr(#) == #:=#+1 {increase a variable by unity}
  126. @d decr(#) == #:=#-1 {decrease a variable by unity}
  127. @d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
  128. @d do_nothing == {empty statement}
  129. @d return == goto exit {terminate a procedure call}
  130. @f return == nil
  131. @f loop == xclause
  132. @ We assume that |case| statements may include a default case that applies
  133. if no matching label is found. Thus, we shall use constructions like
  134. @^system dependencies@>
  135. $$\vbox{\halign{#\hfil\cr
  136. |case x of|\cr
  137. 1: $\langle\,$code for $x=1\,\rangle$;\cr
  138. 3: $\langle\,$code for $x=3\,\rangle$;\cr
  139. |othercases| $\langle\,$code for |x<>1| and |x<>3|$\,\rangle$\cr
  140. |endcases|\cr}}$$
  141. since most \PASCAL\ compilers have plugged this hole in the language by
  142. incorporating some sort of default mechanism. For example, the compiler
  143. used to develop \.{WEB} and \TeX\ allows `|others|:' as a default label,
  144. and other \PASCAL s allow syntaxes like `\ignorespaces|else|\unskip' or
  145. `\&{otherwise}' or `\\{otherwise}:', etc. The definitions of |othercases|
  146. and |endcases| should be changed to agree with local conventions.
  147. (Of course, if no default mechanism is available, the |case| statements of
  148. this program must be extended by listing all remaining cases.)
  149. @d othercases == others: {default for cases not listed explicitly}
  150. @d endcases == @+end {follows the default case in an extended |case| statement}
  151. @f othercases == else
  152. @f endcases == end
  153. @ The following parameters are set big enough to handle \TeX, so they
  154. should be sufficient for most applications of \.{WEAVE}.
  155. @<Constants...@>=
  156. @!max_bytes=45000; {|1/ww| times the number of bytes in identifiers,
  157.   index entries, and module names; must be less than 65536}
  158. @!max_names=5000; {number of identifiers, index entries, and module names;
  159.   must be less than 10240}
  160. @!max_modules=2000;{greater than the total number of modules}
  161. @!hash_size=353; {should be prime}
  162. @!buf_size=100; {maximum length of input line}
  163. @!longest_name=400; {module names shouldn't be longer than this}
  164. @!long_buf_size=500; {|buf_size+longest_name|}
  165. @!line_length=80; {lines of \TeX\ output have at most this many characters,
  166.   should be less than 256}
  167. @!max_refs=30000; {number of cross references; must be less than 65536}
  168. @!max_toks=30000; {number of symbols in \PASCAL\ texts being parsed;
  169.   must be less than 65536}
  170. @!max_texts=2000; {number of phrases in \PASCAL\ texts being parsed;
  171.   must be less than 10240}
  172. @!max_scraps=1000; {number of tokens in \PASCAL\ texts being parsed}
  173. @!stack_size=200; {number of simultaneous output levels}
  174. @ A global variable called |history| will contain one of four values
  175. at the end of every run: |spotless| means that no unusual messages were
  176. printed; |harmless_message| means that a message of possible interest
  177. was printed but no serious errors were detected; |error_message| means that
  178. at least one error was found; |fatal_message| means that the program
  179. terminated abnormally. The value of |history| does not influence the
  180. behavior of the program; it is simply computed for the convenience
  181. of systems that might want to use such information.
  182. @d spotless=0 {|history| value for normal jobs}
  183. @d harmless_message=1 {|history| value when non-serious info was printed}
  184. @d error_message=2 {|history| value when an error was noted}
  185. @d fatal_message=3 {|history| value when we had to stop prematurely}
  186. @d mark_harmless==@t@>@+if history=spotless then history:=harmless_message
  187. @d mark_error==history:=error_message
  188. @d mark_fatal==history:=fatal_message
  189. @<Glob...@>=@!history:spotless..fatal_message; {how bad was this run?}
  190. @ @<Set init...@>=history:=spotless;
  191. @* The character set.
  192. One of the main goals in the design of \.{WEB} has been to make it readily
  193. portable between a wide variety of computers. Yet \.{WEB} by its very
  194. nature must use a greater variety of characters than most computer
  195. programs deal with, and character encoding is one of the areas in which
  196. existing machines differ most widely from each other.
  197. To resolve this problem, all input to \.{WEAVE} and \.{TANGLE} is
  198. converted to an internal eight-bit code that is essentially standard
  199. ASCII, the ``American Standard Code for Information Interchange.''
  200. The conversion is done immediately when each character is read in.
  201. Conversely, characters are converted from ASCII to the user's external
  202. representation just before they are output. (The original ASCII code
  203. was seven bits only; \.{WEB} now allows eight bits in an attempt to
  204. keep up with modern times.)
  205. Such an internal code is relevant to users of \.{WEB} only because it is
  206. the code used for preprocessed constants like \.{"A"}. If you are writing
  207. a program in \.{WEB} that makes use of such one-character constants, you
  208. should convert your input to ASCII form, like \.{WEAVE} and \.{TANGLE} do.
  209. Otherwise \.{WEB}'s internal coding scheme does not affect you.
  210. @^ASCII code@>
  211. Here is a table of the standard visible ASCII codes:
  212. $$\def\:{\char\count255\global\advance\count255 by 1}
  213. \count255='40
  214. \vbox{
  215. \hbox{\hbox to 40pt{\it\hfill0\/\hfill}%
  216. \hbox to 40pt{\it\hfill1\/\hfill}%
  217. \hbox to 40pt{\it\hfill2\/\hfill}%
  218. \hbox to 40pt{\it\hfill3\/\hfill}%
  219. \hbox to 40pt{\it\hfill4\/\hfill}%
  220. \hbox to 40pt{\it\hfill5\/\hfill}%
  221. \hbox to 40pt{\it\hfill6\/\hfill}%
  222. \hbox to 40pt{\it\hfill7\/\hfill}}
  223. \vskip 4pt
  224. \hrule
  225. \def\^{\vrule height 10.5pt depth 4.5pt}
  226. \halign{\hbox to 0pt{\hskip -24pt\O{#0}\hfill}&\^
  227. \hbox to 40pt{\tt\hfill#\hfill\^}&
  228. &\hbox to 40pt{\tt\hfill#\hfill\^}\cr
  229. 04&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  230. 05&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  231. 06&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  232. 07&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  233. 10&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  234. 11&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  235. 12&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  236. 13&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  237. 14&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  238. 15&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  239. 16&\:&\:&\:&\:&\:&\:&\:&\:\cr\noalign{\hrule}
  240. 17&\:&\:&\:&\:&\:&\:&\:\cr}
  241. \hrule width 280pt}$$
  242. (Actually, of course, code @'040 is an invisible blank space.)  Code @'136
  243. was once an upward arrow (\.{\char'13}), and code @'137 was
  244. once a left arrow (\.^^X), in olden times when the first draft
  245. of ASCII code was prepared; but \.{WEB} works with today's standard
  246. ASCII in which those codes represent circumflex and underline as shown.
  247. @<Types...@>=
  248. @!ASCII_code=0..255; {eight-bit numbers, a subrange of the integers}
  249. @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
  250. character sets were common, so it did not make provision for lowercase
  251. letters. Nowadays, of course, we need to deal with both capital and small
  252. letters in a convenient way, so \.{WEB} assumes that it is being used
  253. with a \PASCAL\ whose character set contains at least the characters of
  254. standard ASCII as listed above. Some \PASCAL\ compilers use the original
  255. name |char| for the data type associated with the characters in text files,
  256. while other \PASCAL s consider |char| to be a 64-element subrange of a larger
  257. data type that has some other name.
  258. In order to accommodate this difference, we shall use the name |text_char|
  259. to stand for the data type of the characters in the input and output
  260. files.  We shall also assume that |text_char| consists of the elements
  261. |chr(first_text_char)| through |chr(last_text_char)|, inclusive. The
  262. following definitions should be adjusted if necessary.
  263. @^system dependencies@>
  264. @d text_char == char {the data type of characters in text files}
  265. @d first_text_char=0 {ordinal number of the smallest element of |text_char|}
  266. @d last_text_char=255 {ordinal number of the largest element of |text_char|}
  267. @<Types...@>=
  268. @!text_file=packed file of text_char;
  269. @ The \.{WEAVE} and \.{TANGLE} processors convert between ASCII code and
  270. the user's external character set by means of arrays |xord| and |xchr|
  271. that are analogous to \PASCAL's |ord| and |chr| functions.
  272. @<Globals...@>=
  273. @!xord: array [text_char] of ASCII_code;
  274.   {specifies conversion of input characters}
  275. @!xchr: array [ASCII_code] of text_char;
  276.   {specifies conversion of output characters}
  277. @ If we assume that every system using \.{WEB} is able to read and write the
  278. visible characters of standard ASCII (although not necessarily using the
  279. ASCII codes to represent them), the following assignment statements initialize
  280. most of the |xchr| array properly, without needing any system-dependent
  281. changes. For example, the statement \.{xchr[@@\'101]:=\'A\'} that appears
  282. in the present \.{WEB} file might be encoded in, say, {\mc EBCDIC} code
  283. on the external medium on which it resides, but \.{TANGLE} will convert from
  284. this external code to ASCII and back again. Therefore the assignment
  285. statement \.{XCHR[65]:=\'A\'} will appear in the corresponding \PASCAL\ file,
  286. and \PASCAL\ will compile this statement so that |xchr[65]| receives the
  287. character \.A in the external (|char|) code. Note that it would be quite
  288. incorrect to say \.{xchr[@@\'101]:="A"}, because |"A"| is a constant of
  289. type |integer|, not |char|, and because we have $|"A"|=65$ regardless of
  290. the external character set.
  291. @<Set init...@>=
  292. xchr[@'40]:=' ';
  293. xchr[@'41]:='!';
  294. xchr[@'42]:='"';
  295. xchr[@'43]:='#';
  296. xchr[@'44]:='$';
  297. xchr[@'45]:='%';
  298. xchr[@'46]:='&';
  299. xchr[@'47]:='''';@/
  300. xchr[@'50]:='(';
  301. xchr[@'51]:=')';
  302. xchr[@'52]:='*';
  303. xchr[@'53]:='+';
  304. xchr[@'54]:=',';
  305. xchr[@'55]:='-';
  306. xchr[@'56]:='.';
  307. xchr[@'57]:='/';@/
  308. xchr[@'60]:='0';
  309. xchr[@'61]:='1';
  310. xchr[@'62]:='2';
  311. xchr[@'63]:='3';
  312. xchr[@'64]:='4';
  313. xchr[@'65]:='5';
  314. xchr[@'66]:='6';
  315. xchr[@'67]:='7';@/
  316. xchr[@'70]:='8';
  317. xchr[@'71]:='9';
  318. xchr[@'72]:=':';
  319. xchr[@'73]:=';';
  320. xchr[@'74]:='<';
  321. xchr[@'75]:='=';
  322. xchr[@'76]:='>';
  323. xchr[@'77]:='?';@/
  324. xchr[@'100]:='@@';
  325. xchr[@'101]:='A';
  326. xchr[@'102]:='B';
  327. xchr[@'103]:='C';
  328. xchr[@'104]:='D';
  329. xchr[@'105]:='E';
  330. xchr[@'106]:='F';
  331. xchr[@'107]:='G';@/
  332. xchr[@'110]:='H';
  333. xchr[@'111]:='I';
  334. xchr[@'112]:='J';
  335. xchr[@'113]:='K';
  336. xchr[@'114]:='L';
  337. xchr[@'115]:='M';
  338. xchr[@'116]:='N';
  339. xchr[@'117]:='O';@/
  340. xchr[@'120]:='P';
  341. xchr[@'121]:='Q';
  342. xchr[@'122]:='R';
  343. xchr[@'123]:='S';
  344. xchr[@'124]:='T';
  345. xchr[@'125]:='U';
  346. xchr[@'126]:='V';
  347. xchr[@'127]:='W';@/
  348. xchr[@'130]:='X';
  349. xchr[@'131]:='Y';
  350. xchr[@'132]:='Z';
  351. xchr[@'133]:='[';
  352. xchr[@'134]:='\';
  353. xchr[@'135]:=']';
  354. xchr[@'136]:='^';
  355. xchr[@'137]:='_';@/
  356. xchr[@'140]:='`';
  357. xchr[@'141]:='a';
  358. xchr[@'142]:='b';
  359. xchr[@'143]:='c';
  360. xchr[@'144]:='d';
  361. xchr[@'145]:='e';
  362. xchr[@'146]:='f';
  363. xchr[@'147]:='g';@/
  364. xchr[@'150]:='h';
  365. xchr[@'151]:='i';
  366. xchr[@'152]:='j';
  367. xchr[@'153]:='k';
  368. xchr[@'154]:='l';
  369. xchr[@'155]:='m';
  370. xchr[@'156]:='n';
  371. xchr[@'157]:='o';@/
  372. xchr[@'160]:='p';
  373. xchr[@'161]:='q';
  374. xchr[@'162]:='r';
  375. xchr[@'163]:='s';
  376. xchr[@'164]:='t';
  377. xchr[@'165]:='u';
  378. xchr[@'166]:='v';
  379. xchr[@'167]:='w';@/
  380. xchr[@'170]:='x';
  381. xchr[@'171]:='y';
  382. xchr[@'172]:='z';
  383. xchr[@'173]:='{';
  384. xchr[@'174]:='|';
  385. xchr[@'175]:='}';
  386. xchr[@'176]:='~';@/
  387. xchr[0]:=' '; xchr[@'177]:=' '; {these ASCII codes are not used}
  388. @ Some of the ASCII codes below @'40 have been given symbolic names in
  389. \.{WEAVE} and \.{TANGLE} because they are used with a special meaning.
  390. @d and_sign=@'4 {equivalent to `\.{and}'}
  391. @d not_sign=@'5 {equivalent to `\.{not}'}
  392. @d set_element_sign=@'6 {equivalent to `\.{in}'}
  393. @d tab_mark=@'11 {ASCII code used as tab-skip}
  394. @d line_feed=@'12 {ASCII code thrown away at end of line}
  395. @d form_feed=@'14 {ASCII code used at end of page}
  396. @d carriage_return=@'15 {ASCII code used at end of line}
  397. @d left_arrow=@'30 {equivalent to `\.{:=}'}
  398. @d not_equal=@'32 {equivalent to `\.{<>}'}
  399. @d less_or_equal=@'34 {equivalent to `\.{<=}'}
  400. @d greater_or_equal=@'35 {equivalent to `\.{>=}'}
  401. @d equivalence_sign=@'36 {equivalent to `\.{==}'}
  402. @d or_sign=@'37 {equivalent to `\.{or}'}
  403. @ When we initialize the |xord| array and the remaining parts of |xchr|,
  404. it will be convenient to make use of an index variable, |i|.
  405. @<Local variables for init...@>=
  406. @!i:0..255;
  407. @ Here now is the system-dependent part of the character set.
  408. If \.{WEB} is being implemented on a garden-variety \PASCAL\ for which
  409. only standard ASCII codes will appear in the input and output files, you
  410. don't need to make any changes here. But if you have, for example, an extended
  411. character set like the one in Appendix~C of {\sl The \TeX book}, the first
  412. line of code in this module should be changed to
  413. $$\hbox{|for i:=1 to @'37 do xchr[i]:=chr(i);|}$$
  414. \.{WEB}'s character set is essentially identical to \TeX's, even with respect to
  415. characters less than @'40.
  416. @^system dependencies@>
  417. Changes to the present module will make \.{WEB} more friendly on computers
  418. that have an extended character set, so that one can type things like
  419. \.^^Z\ instead of \.{<>}. If you have an extended set of characters that
  420. are easily incorporated into text files, you can assign codes arbitrarily
  421. here, giving an |xchr| equivalent to whatever characters the users of
  422. \.{WEB} are allowed to have in their input files, provided that unsuitable
  423. characters do not correspond to special codes like |carriage_return|
  424. that are listed above.
  425. (The present file \.{WEAVE.WEB} does not contain any of the non-ASCII
  426. characters, because it is intended to be used with all implementations of
  427. \.{WEB}.  It was originally created on a Stanford system that has a
  428. convenient extended character set, then ``sanitized'' by applying another
  429. program that transliterated all of the non-standard characters into
  430. standard equivalents.)
  431. @<Set init...@>=
  432. for i:=1 to @'37 do xchr[i]:=' ';
  433. for i:=@'200 to @'377 do xchr[i]:=' ';
  434. @ The following system-independent code makes the |xord| array contain a
  435. suitable inverse to the information in |xchr|.
  436. @<Set init...@>=
  437. for i:=first_text_char to last_text_char do xord[chr(i)]:=" ";
  438. for i:=1 to @'377 do xord[xchr[i]]:=i;
  439. xord[' ']:=" ";
  440. @* Input and output.
  441. The input conventions of this program are intended to be very much like those
  442. of \TeX\ (except, of course, that they are much simpler, because much less
  443. needs to be done). Furthermore they are identical to those of \.{TANGLE}.
  444. Therefore people who need to make modifications to all three systems
  445. should be able to do so without too many headaches.
  446. We use the standard \PASCAL\ input/output procedures in several places that
  447. \TeX\ cannot, since \.{WEAVE} does not have to deal with files that are named
  448. dynamically by the user, and since there is no input from the terminal.
  449. @ Terminal output is done by writing on file |term_out|, which is assumed to
  450. consist of characters of type |text_char|:
  451. @^system dependencies@>
  452. @d print(#)==write(term_out,#) {`|print|' means write on the terminal}
  453. @d print_ln(#)==write_ln(term_out,#) {`|print|' and then start new line}
  454. @d new_line==write_ln(term_out) {start new line}
  455. @d print_nl(#)==  {print information starting on a new line}
  456.   begin new_line; print(#);
  457.   end
  458. @<Globals...@>=
  459. @!term_out:text_file; {the terminal as an output file}
  460. @ Different systems have different ways of specifying that the output on a
  461. certain file will appear on the user's terminal. Here is one way to do this
  462. on the \PASCAL\ system that was used in \.{TANGLE}'s initial development:
  463. @^system dependencies@>
  464. @<Set init...@>=
  465. rewrite(term_out,'TTY:'); {send |term_out| output to the terminal}
  466. @ The |update_terminal| procedure is called when we want
  467. to make sure that everything we have output to the terminal so far has
  468. actually left the computer's internal buffers and been sent.
  469. @^system dependencies@>
  470. @d update_terminal == break(term_out) {empty the terminal output buffer}
  471. @ The main input comes from |web_file|; this input may be overridden
  472. by changes in |change_file|. (If |change_file| is empty, there are no changes.)
  473. @<Globals...@>=
  474. @!web_file:text_file; {primary input}
  475. @!change_file:text_file; {updates}
  476. @ The following code opens the input files.  Since these files were listed
  477. in the program header, we assume that the \PASCAL\ runtime system has
  478. already checked that suitable file names have been given; therefore no
  479. additional error checking needs to be done. We will see below that
  480. \.{WEAVE} reads through the entire input twice.
  481. @^system dependencies@>
  482. @p procedure open_input; {prepare to read |web_file| and |change_file|}
  483. begin reset(web_file); reset(change_file);
  484. @ The main output goes to |tex_file|.
  485. @<Globals...@>=
  486. @!tex_file: text_file;
  487. @ The following code opens |tex_file|.
  488. Since this file was listed in the program header, we assume that the
  489. \PASCAL\ runtime system has checked that a suitable external file name has
  490. been given.
  491. @^system dependencies@>
  492. @<Set init...@>=
  493. rewrite(tex_file);
  494. @ Input goes into an array called |buffer|.
  495. @<Globals...@>=@!buffer: array[0..long_buf_size] of ASCII_code;
  496. @ The |input_ln| procedure brings the next line of input from the specified
  497. file into the |buffer| array and returns the value |true|, unless the file has
  498. already been entirely read, in which case it returns |false|. The conventions
  499. of \TeX\ are followed; i.e., |ASCII_code| numbers representing the next line
  500. of the file are input into |buffer[0]|, |buffer[1]|, \dots,
  501. |buffer[limit-1]|; trailing blanks are ignored;
  502. and the global variable |limit| is set to the length of the
  503. @^system dependencies@>
  504. line. The value of |limit| must be strictly less than |buf_size|.
  505. We assume that none of the |ASCII_code| values
  506. of |buffer[j]| for |0<=j<limit| is equal to 0, @'177, |line_feed|, |form_feed|,
  507. or |carriage_return|. Since |buf_size| is strictly less than |long_buf_size|,
  508. some of \.{WEAVE}'s routines use the fact that it is safe to refer to
  509. |buffer[limit+2]| without overstepping the bounds of the array.
  510. @p function input_ln(var f:text_file):boolean;
  511.   {inputs a line or returns |false|}
  512. var final_limit:0..buf_size; {|limit| without trailing blanks}
  513. begin limit:=0; final_limit:=0;
  514. if eof(f) then input_ln:=false
  515. else  begin while not eoln(f) do
  516.     begin buffer[limit]:=xord[f^]; get(f);
  517.     incr(limit);
  518.     if buffer[limit-1]<>" " then final_limit:=limit;
  519.     if limit=buf_size then
  520.       begin while not eoln(f) do get(f);
  521.       decr(limit); {keep |buffer[buf_size]| empty}
  522.       if final_limit>limit then final_limit:=limit;
  523.       print_nl('! Input line too long'); loc:=0; error;
  524. @.Input line too long@>
  525.       end;
  526.     end;
  527.   read_ln(f); limit:=final_limit; input_ln:=true;
  528.   end;
  529. @* Reporting errors to the user.
  530. The \.{WEAVE} processor operates in three phases: first it inputs the source
  531. file and stores cross-reference data, then it inputs the source once again and
  532. produces the \TeX\ output file, and finally it sorts and outputs the index.
  533. The global variables |phase_one| and |phase_three| tell which Phase we are in.
  534. @<Globals...@>=
  535. @!phase_one: boolean; {|true| in Phase I, |false| in Phases II and III}
  536. @!phase_three: boolean; {|true| in Phase III, |false| in Phases I and II}
  537. @ If an error is detected while we are debugging,
  538. we usually want to look at the contents of memory.
  539. A special procedure will be declared later for this purpose.
  540. @<Error handling...@>=
  541. @!debug@+ procedure debug_help; forward;@+gubed
  542. @ The command `|err_print('! Error message')|' will report a syntax error to
  543. the user, by printing the error message at the beginning of a new line and
  544. then giving an indication of where the error was spotted in the source file.
  545. Note that no period follows the error message, since the error routine
  546. will automatically supply a period.
  547. The actual error indications are provided by a procedure called |error|.
  548. However, error messages are not actually reported during phase one,
  549. since errors detected on the first pass will be detected again
  550. during the second.
  551. @d err_print(#)==
  552.   begin if not phase_one then
  553.     begin new_line; print(#); error;
  554.     end;
  555.   end
  556. @<Error handling...@>=
  557. procedure error; {prints `\..' and location of error message}
  558. var@!k,@!l: 0..long_buf_size; {indices into |buffer|}
  559. begin @<Print error location based on input buffer@>;
  560. update_terminal; mark_error;
  561. @!debug debug_skipped:=debug_cycle;debug_help;@+gubed
  562. @ The error locations can be indicated by using the global variables
  563. |loc|, |line|, and |changing|, which tell respectively the first
  564. unlooked-at position in |buffer|, the current line number, and whether or not
  565. the current line is from |change_file| or |web_file|.
  566. This routine should be modified on systems whose standard text editor
  567. has special line-numbering conventions.
  568. @^system dependencies@>
  569. @<Print error location based on input buffer@>=
  570. begin if changing then print('. (change file ')@+else print('. (');
  571. print_ln('l.', line:1, ')');
  572. if loc>=limit then l:=limit else l:=loc;
  573. for k:=1 to l do
  574.   if buffer[k-1]=tab_mark then print(' ')
  575.   else print(xchr[buffer[k-1]]); {print the characters already read}
  576. new_line;
  577. for k:=1 to l do print(' '); {space out the next line}
  578. for k:=l+1 to limit do print(xchr[buffer[k-1]]); {print the part not yet read}
  579. if buffer[limit]="|" then print(xchr["|"]);
  580.   {end of \PASCAL\ text in module names}
  581. print(' '); {this space separates the message from future asterisks}
  582. @ The |jump_out| procedure just cuts across all active procedure levels
  583. and jumps out of the program. This is the only non-local \&{goto} statement
  584. in \.{WEAVE}. It is used when no recovery from a particular error has
  585. been provided.
  586. Some \PASCAL\ compilers do not implement non-local |goto| statements.
  587. @^system dependencies@>
  588. In such cases the code that appears at label |end_of_WEAVE| should be
  589. copied into the |jump_out| procedure, followed by a call to a system procedure
  590. that terminates the program.
  591. @d fatal_error(#)==begin new_line; print(#); error; mark_fatal; jump_out;
  592.   end
  593. @<Error handling...@>=
  594. procedure jump_out;
  595. begin goto end_of_WEAVE;
  596. @ Sometimes the program's behavior is far different from what it should be,
  597. and \.{WEAVE} prints an error message that is really for the \.{WEAVE}
  598. maintenance person, not the user. In such cases the program says
  599. |confusion('indication of where we are')|.
  600. @d confusion(#)==fatal_error('! This can''t happen (',#,')')
  601. @.This can't happen@>
  602. @ An overflow stop occurs if \.{WEAVE}'s tables aren't large enough.
  603. @d overflow(#)==fatal_error('! Sorry, ',#,' capacity exceeded')
  604. @.Sorry, x capacity exceeded@>
  605. @* Data structures.
  606. During the first phase of its processing, \.{WEAVE} puts identifier names,
  607. index entries, and module names into the large |byte_mem| array, which is
  608. packed with eight-bit integers. Allocation is sequential, since names are
  609. never deleted.
  610. An auxiliary array |byte_start| is used as a directory for |byte_mem|,
  611. and the |link|, |ilk|, and |xref| arrays give further information about names.
  612. These auxiliary arrays consist of sixteen-bit items.
  613. @<Types...@>=
  614. @!eight_bits=0..255; {unsigned one-byte quantity}
  615. @!sixteen_bits=0..65535; {unsigned two-byte quantity}
  616. @ \.{WEAVE} has been designed to avoid the need for indices that are more
  617. than sixteen bits wide, so that it can be used on most computers. But
  618. there are programs that need more than 65536 bytes; \TeX\ is one of these.
  619. To get around this problem, a slight complication has been added to the
  620. data structures:  |byte_mem| is a two-dimensional array, whose first index
  621. is either 0 or 1. (For generality, the first index is actually allowed to
  622. run between 0 and |ww-1|, where |ww| is defined to be 2; the program will
  623. work for any positive value of |ww|, and it can be simplified in obvious
  624. ways if |ww=1|.)
  625. @d ww=2 {we multiply the byte capacity by approximately this amount}
  626. @<Globals...@>=
  627. @!byte_mem: packed array [0..ww-1,0..max_bytes] of ASCII_code;
  628.   {characters of names}
  629. @!byte_start: array [0..max_names] of sixteen_bits; {directory into |byte_mem|}
  630. @!link: array [0..max_names] of sixteen_bits; {hash table or tree links}
  631. @!ilk: array [0..max_names] of sixteen_bits; {type codes or tree links}
  632. @!xref: array [0..max_names] of sixteen_bits; {heads of cross-reference lists}
  633. @ The names of identifiers are found by computing a hash address |h| and
  634. then looking at strings of bytes signified by |hash[h]|, |link[hash[h]]|,
  635. |link[link[hash[h]]]|, \dots, until either finding the desired name
  636. or encountering a zero.
  637. A `|name_pointer|' variable, which signifies a name, is an index into
  638. |byte_start|. The actual sequence of characters in the name pointed to by
  639. |p| appears in positions |byte_start[p]| to |byte_start[p+ww]-1|, inclusive,
  640. in the segment of |byte_mem| whose first index is |p mod ww|. Thus, when
  641. |ww=2| the even-numbered name bytes appear in |byte_mem[0,@t$*$@>]|
  642. and the odd-numbered ones appear in |byte_mem[1,@t$*$@>]|.
  643. The pointer 0 is used for undefined module names; we don't
  644. want to use it for the names of identifiers, since 0 stands for a null
  645. pointer in a linked list.
  646. We usually have |byte_start[name_ptr+w]=byte_ptr[(name_ptr+w) mod ww]|
  647. for |0<=w<ww|, since these are the starting positions for the next |ww|
  648. names to be stored in |byte_mem|.
  649. @d length(#)==byte_start[#+ww]-byte_start[#] {the length of a name}
  650. @<Types...@>=
  651. @!name_pointer=0..max_names; {identifies a name}
  652. @ @<Global...@>=
  653. @!name_ptr:name_pointer; {first unused position in |byte_start|}
  654. @!byte_ptr:array [0..ww-1] of 0..max_bytes;
  655.   {first unused position in |byte_mem|}
  656. @ @<Local variables for init...@>=
  657. @!wi: 0..ww-1; {to initialize the |byte_mem| indices}
  658. @ @<Set init...@>=
  659. for wi:=0 to ww-1 do
  660.   begin byte_start[wi]:=0; byte_ptr[wi]:=0;
  661.   end;
  662. byte_start[ww]:=0; {this makes name 0 of length zero}
  663. name_ptr:=1;
  664. @ Several types of identifiers are distinguished by their |ilk|:
  665. \yskip\hang |normal| identifiers are part of the \PASCAL\ program and
  666. will appear in italic type.
  667. \yskip\hang |roman| identifiers are index entries that appear after
  668. \.{@@\^} in the \.{WEB} file.
  669. \yskip\hang |wildcard| identifiers are index entries that appear after
  670. \.{@@:} in the \.{WEB} file.
  671. \yskip\hang |typewriter| identifiers are index entries that appear after
  672. \.{@@.} in the \.{WEB} file.
  673. \yskip\hang |array_like|, |begin_like|, \dots, |var_like|
  674. identifiers are \PASCAL\ reserved words whose |ilk| explains how they are
  675. to be treated when \PASCAL\ code is being formatted.
  676. \yskip\hang Finally, if |c| is an ASCII code, an |ilk| equal to
  677. |char_like+c| denotes a reserved word that will be converted to character
  678. @d normal=0 {ordinary identifiers have |normal| ilk}
  679. @d roman=1 {normal index entries have |roman| ilk}
  680. @d wildcard=2 {user-formatted index entries have |wildcard| ilk}
  681. @d typewriter=3 {`typewriter type' entries have |typewriter| ilk}
  682. @d reserved(#)==(ilk[#]>typewriter) {tells if a name is a reserved word}
  683. @d array_like=4 {\&{array}, \&{file}, \&{set}}
  684. @d begin_like=5 {\&{begin}}
  685. @d case_like=6 {\&{case}}
  686. @d const_like=7 {\&{const}, \&{label}, \&{type}}
  687. @d div_like=8 {\&{div}, \&{mod}}
  688. @d do_like=9 {\&{do}, \&{of}, \&{then}}
  689. @d else_like=10 {\&{else}}
  690. @d end_like=11 {\&{end}}
  691. @d for_like=12 {\&{for}, \&{while}, \&{with}}
  692. @d goto_like=13 {\&{goto}, \&{packed}}
  693. @d if_like=14 {\&{if}}
  694. @d in_like=15 {\&{in}}
  695. @d nil_like=16 {\&{nil}}
  696. @d proc_like=17 {\&{function}, \&{procedure}, \&{program}}
  697. @d record_like=18 {\&{record}}
  698. @d repeat_like=19 {\&{repeat}}
  699. @d to_like=20 {\&{downto}, \&{to}}
  700. @d until_like=21 {\&{until}}
  701. @d var_like=22 {\&{var}}
  702. @d loop_like=23 {\&{loop}, \&{xclause}}
  703. @d char_like=24 {\&{and}, \&{or}, \&{not}, \&{in}}
  704. @ The names of modules are stored in |byte_mem| together
  705. with the identifier names, but a hash table is not used for them because
  706. \.{WEAVE} needs to be able to recognize a module name when given a prefix of
  707. that name. A conventional binary seach tree is used to retrieve module names,
  708. with fields called |llink| and |rlink| in place of |link| and |ilk|. The
  709. root of this tree is |rlink[0]|.
  710. @d llink==link {left link in binary search tree for module names}
  711. @d rlink==ilk {right link in binary search tree for module names}
  712. @d root==rlink[0] {the root of the binary search tree for module names}
  713. @<Set init...@>=
  714. root:=0; {the binary search tree starts out with nothing in it}
  715. @ Here is a little procedure that prints the text of a given name on the
  716. user's terminal.
  717. @p procedure print_id(@!p:name_pointer); {print identifier or module name}
  718. var k:0..max_bytes; {index into |byte_mem|}
  719. @!w:0..ww-1; {row of |byte_mem|}
  720. begin if p>=name_ptr then print('IMPOSSIBLE')
  721. else  begin w:=p mod ww;
  722.   for k:=byte_start[p] to byte_start[p+ww]-1 do
  723.     print(xchr[byte_mem[w,k]]);
  724.   end;
  725. @ We keep track of the current module number in
  726. |module_count|, which is the total number of modules that have started.
  727. Modules which have been altered by a change file entry
  728. have their |changed_module| flag turned on during the first phase.
  729. @<Globals...@>=
  730. @!module_count:0..max_modules; {the current module number}
  731. @!changed_module: packed array [0..max_modules] of boolean; {is it changed?}
  732. @!change_exists: boolean; {has any module changed?}
  733. @ The other large memory area in \.{WEAVE} keeps the cross-reference data.
  734. All uses of the name |p| are recorded in a linked list beginning at
  735. |xref[p]|, which points into the |xmem| array. Entries in |xmem| consist
  736. of two sixteen-bit items per word, called the |num| and |xlink| fields.
  737. If |x| is an index into |xmem|, reached from name |p|, the value of |num(x)|
  738. is either a module number where |p| is used, or it is |def_flag| plus a
  739. module number where |p| is defined; and |xlink(x)| points to the next such
  740. cross reference for |p|, if any. This list of cross references is in
  741. decreasing order by module number. The current number of cross references
  742. is |xref_ptr|.
  743. The global variable |xref_switch| is set either to |def_flag| or to zero,
  744. depending on whether the next cross reference to an identifier is to be
  745. underlined or not in the index. This switch is set to |def_flag| when
  746. \.{@@!} or \.{@@d} or \.{@@f} is scanned, and it is cleared to zero when
  747. the next identifier or index entry cross reference has been made. Similarly,
  748. the global variable |mod_xref_switch| is either |def_flag| or zero, depending
  749. on whether a module name is being defined or used.
  750. @d num(#)==xmem[#].num_field
  751. @d xlink(#)==xmem[#].xlink_field
  752. @d def_flag=10240 {must be strictly larger than |max_modules|}
  753. @ @<Types...@>=
  754. @!xref_number=0..max_refs;
  755. @ @<Globals...@>=
  756. @!xmem:array[xref_number] of packed record@t@>@/
  757.   @!num_field: sixteen_bits; {module number plus zero or |def_flag|}
  758.   @!xlink_field: sixteen_bits; {pointer to the previous cross reference}
  759.   end;
  760. @!xref_ptr:xref_number; {the largest occupied position in |xmem|}
  761. @!xref_switch,@!mod_xref_switch:0..def_flag; {either zero or |def_flag|}
  762. @ @<Set init...@>=xref_ptr:=0; xref_switch:=0; mod_xref_switch:=0; num(0):=0;
  763. xref[0]:=0; {cross references to undefined modules}
  764. @ A new cross reference for an identifier is formed by calling |new_xref|,
  765. which discards duplicate entries and ignores non-underlined references
  766. to one-letter identifiers or \PASCAL's reserved words.
  767. @d append_xref(#)==if xref_ptr=max_refs then overflow('cross reference')
  768.   else  begin incr(xref_ptr); num(xref_ptr):=#;
  769.     end
  770. @p procedure new_xref(@!p:name_pointer);
  771. label exit;
  772. var q:xref_number; {pointer to previous cross reference}
  773. @!m,@!n: sixteen_bits; {new and previous cross-reference value}
  774. begin if (reserved(p)or(byte_start[p]+1=byte_start[p+ww]))and
  775.   (xref_switch=0) then return;
  776. m:=module_count+xref_switch; xref_switch:=0; q:=xref[p];
  777. if q>0 then
  778.   begin n:=num(q);
  779.   if (n=m)or(n=m+def_flag) then return
  780.   else if m=n+def_flag then
  781.     begin num(q):=m; return;
  782.     end;
  783.   end;
  784. append_xref(m); xlink(xref_ptr):=q; xref[p]:=xref_ptr;
  785. exit: end;
  786. @ The cross reference lists for module names are slightly different. Suppose
  787. that a module name is defined in modules $m_1$, \dots, $m_k$ and used in
  788. modules $n_1$, \dots, $n_l$. Then its list will contain $m_1+|def_flag|$,
  789. $m_k+|def_flag|$, \dots, $m_2+|def_flag|$, $n_l$, \dots, $n_1$, in
  790. this order.  After Phase II, however, the order will be
  791. $m_1+|def_flag|$, \dots, $m_k+|def_flag|$, $n_1$, \dots, $n_l$.
  792. @p procedure new_mod_xref(@!p:name_pointer);
  793. var q,@!r:xref_number; {pointers to previous cross references}
  794. begin q:=xref[p]; r:=0;
  795. if q>0 then
  796.   begin if mod_xref_switch=0 then while num(q)>=def_flag do
  797.     begin r:=q; q:=xlink(q);
  798.     end
  799.   else if num(q)>=def_flag then
  800.     begin r:=q; q:=xlink(q);
  801.     end;
  802.   end;
  803. append_xref(module_count+mod_xref_switch); xlink(xref_ptr):=q;
  804. mod_xref_switch:=0;
  805. if r=0 then xref[p]:=xref_ptr
  806. else xlink(r):=xref_ptr;
  807. @ A third large area of memory is used for sixteen-bit `tokens', which appear
  808. in short lists similar to the strings of characters in |byte_mem|. Token lists
  809. are used to contain the result of \PASCAL\ code translated into \TeX\ form;
  810. further details about them will be explained later. A |text_pointer| variable
  811. is an index into |tok_start|.
  812. @<Types...@>=
  813. @!text_pointer=0..max_texts; {identifies a token list}
  814. @ The first position of |tok_mem|
  815. that is unoccupied by replacement text is called |tok_ptr|, and the first
  816. unused location of |tok_start| is called |text_ptr|.
  817. Thus, we usually have |tok_start[text_ptr]=tok_ptr|.
  818. @<Glob...@>=
  819. @t\hskip1em@>@!tok_mem: packed array [0..max_toks] of sixteen_bits; {tokens}
  820. @t\hskip1em@>@!tok_start: array [text_pointer] of sixteen_bits;
  821.   {directory into |tok_mem|}
  822. @t\hskip1em@>@!text_ptr:text_pointer; {first unused position in |tok_start|}
  823. @t\hskip1em@>@!tok_ptr:0..max_toks; {first unused position in |tok_mem|}
  824. stat@!max_tok_ptr,@!max_txt_ptr:0..max_toks; {largest values occurring}
  825. @ @<Set init...@>=
  826. tok_ptr:=1; text_ptr:=1; tok_start[0]:=1; tok_start[1]:=1;
  827. stat max_tok_ptr:=1; max_txt_ptr:=1;@+tats
  828. @* Searching for identifiers.
  829. The hash table described above is updated by the |id_lookup| procedure,
  830. which finds a given identifier and returns a pointer to its index in
  831. |byte_start|. The identifier is supposed to match character by character
  832. and it is also supposed to have a given |ilk| code; the same name may be
  833. present more than once if it is supposed to appear in the index with
  834. different typesetting conventions.
  835. If the identifier was not already present, it is inserted into the table.
  836. Because of the way \.{WEAVE}'s scanning mechanism works, it is most convenient
  837. to let |id_lookup| search for an identifier that is present in the |buffer|
  838. array. Two other global variables specify its position in the buffer: the
  839. first character is |buffer[id_first]|, and the last is |buffer[id_loc-1]|.
  840. @<Glob...@>=
  841. @!id_first:0..long_buf_size; {where the current identifier begins in the buffer}
  842. @!id_loc:0..long_buf_size; {just after the current identifier in the buffer}
  843. @!hash:array [0..hash_size] of sixteen_bits; {heads of hash lists}
  844. @ Initially all the hash lists are empty.
  845. @<Local variables for init...@>=
  846. @!h:0..hash_size; {index into hash-head array}
  847. @ @<Set init...@>=
  848. for h:=0 to hash_size-1 do hash[h]:=0;
  849. @ Here now is the main procedure for finding identifiers (and index
  850. entries).  The parameter |t| is set to the desired |ilk| code. The
  851. identifier must either have |ilk=t|, or we must have
  852. |t=normal| and the identifier must be a reserved word.
  853. @p function id_lookup(@!t:eight_bits):name_pointer; {finds current identifier}
  854. label found;
  855. var i:0..long_buf_size; {index into |buffer|}
  856. @!h:0..hash_size; {hash code}
  857. @!k:0..max_bytes; {index into |byte_mem|}
  858. @!w:0..ww-1; {row of |byte_mem|}
  859. @!l:0..long_buf_size; {length of the given identifier}
  860. @!p:name_pointer; {where the identifier is being sought}
  861. begin l:=id_loc-id_first; {compute the length}
  862. @<Compute the hash code |h|@>;
  863. @<Compute the name location |p|@>;
  864. if p=name_ptr then @<Enter a new name into the table at position |p|@>;
  865. id_lookup:=p;
  866. @ A simple hash code is used: If the sequence of
  867. ASCII codes is $c_1c_2\ldots c_m$, its hash value will be
  868. $$(2^{n-1}c_1+2^{n-2}c_2+\cdots+c_n)\,\bmod\,|hash_size|.$$
  869. @<Compute the hash...@>=
  870. h:=buffer[id_first]; i:=id_first+1;
  871. while i<id_loc do
  872.   begin h:=(h+h+buffer[i]) mod hash_size; incr(i);
  873.   end
  874. @ If the identifier is new, it will be placed in position |p=name_ptr|,
  875. otherwise |p| will point to its existing location.
  876. @<Compute the name location...@>=
  877. p:=hash[h];
  878. while p<>0 do
  879.   begin if (length(p)=l)and((ilk[p]=t)or((t=normal)and reserved(p))) then
  880.     @<Compare name |p| with current identifier,
  881.       |goto found| if equal@>;
  882.   p:=link[p];
  883.   end;
  884. p:=name_ptr; {the current identifier is new}
  885. link[p]:=hash[h]; hash[h]:=p; {insert |p| at beginning of hash list}
  886. found:
  887. @ @<Compare name |p|...@>=
  888. begin i:=id_first; k:=byte_start[p]; w:=p mod ww;
  889. while (i<id_loc)and(buffer[i]=byte_mem[w,k]) do
  890.   begin incr(i); incr(k);
  891.   end;
  892. if i=id_loc then goto found; {all characters agree}
  893. @ When we begin the following segment of the program, |p=name_ptr|.
  894. @<Enter a new name...@>=
  895. begin w:=name_ptr mod ww;
  896. if byte_ptr[w]+l>max_bytes then overflow('byte memory');
  897. if name_ptr+ww>max_names then overflow('name');
  898. i:=id_first; k:=byte_ptr[w]; {get ready to move the identifier into |byte_mem|}
  899. while i<id_loc do
  900.   begin byte_mem[w,k]:=buffer[i]; incr(k); incr(i);
  901.   end;
  902. byte_ptr[w]:=k; byte_start[name_ptr+ww]:=k; incr(name_ptr);
  903. ilk[p]:=t; xref[p]:=0;
  904. @* Initializing the table of reserved words.
  905. We have to get \PASCAL's reserved words into the hash table, and the
  906. simplest way to do this is to insert them every time \.{WEAVE} is run.
  907. A few macros permit us to do the initialization with a compact program.
  908. @d sid9(#)==buffer[9]:=#;cur_name:=id_lookup
  909. @d sid8(#)==buffer[8]:=#;sid9
  910. @d sid7(#)==buffer[7]:=#;sid8
  911. @d sid6(#)==buffer[6]:=#;sid7
  912. @d sid5(#)==buffer[5]:=#;sid6
  913. @d sid4(#)==buffer[4]:=#;sid5
  914. @d sid3(#)==buffer[3]:=#;sid4
  915. @d sid2(#)==buffer[2]:=#;sid3
  916. @d sid1(#)==buffer[1]:=#;sid2
  917. @d id2==id_first:=8; sid8
  918. @d id3==id_first:=7; sid7
  919. @d id4==id_first:=6; sid6
  920. @d id5==id_first:=5; sid5
  921. @d id6==id_first:=4; sid4
  922. @d id7==id_first:=3; sid3
  923. @d id8==id_first:=2; sid2
  924. @d id9==id_first:=1; sid1
  925. @<Globals...@>=
  926. @!cur_name:name_pointer; {points to the identifier just inserted}
  927. @ The intended use of the macros above might not be immediately obvious,
  928. but the riddle is answered by the following:
  929. @<Store all the reserved words@>=
  930. id_loc:=10;@/
  931. id3("a")("n")("d")(char_like+and_sign);@/
  932. id5("a")("r")("r")("a")("y")(array_like);@/
  933. id5("b")("e")("g")("i")("n")(begin_like);@/
  934. id4("c")("a")("s")("e")(case_like);@/
  935. id5("c")("o")("n")("s")("t")(const_like);@/
  936. id3("d")("i")("v")(div_like);@/
  937. id2("d")("o")(do_like);@/
  938. id6("d")("o")("w")("n")("t")("o")(to_like);@/
  939. id4("e")("l")("s")("e")(else_like);@/
  940. id3("e")("n")("d")(end_like);@/
  941. id4("f")("i")("l")("e")(array_like);@/
  942. id3("f")("o")("r")(for_like);@/
  943. id8("f")("u")("n")("c")("t")("i")("o")("n")(proc_like);@/
  944. id4("g")("o")("t")("o")(goto_like);@/
  945. id2("i")("f")(if_like);@/
  946. id2("i")("n")(char_like+set_element_sign);@/
  947. id5("l")("a")("b")("e")("l")(const_like);@/
  948. id3("m")("o")("d")(div_like);@/
  949. id3("n")("i")("l")(nil_like);@/
  950. id3("n")("o")("t")(char_like+not_sign);@/
  951. id2("o")("f")(do_like);@/
  952. id2("o")("r")(char_like+or_sign);@/
  953. id6("p")("a")("c")("k")("e")("d")(goto_like);@/
  954. id9("p")("r")("o")("c")("e")("d")("u")("r")("e")(proc_like);@/
  955. id7("p")("r")("o")("g")("r")("a")("m")(proc_like);@/
  956. id6("r")("e")("c")("o")("r")("d")(record_like);@/
  957. id6("r")("e")("p")("e")("a")("t")(repeat_like);@/
  958. id3("s")("e")("t")(array_like);@/
  959. id4("t")("h")("e")("n")(do_like);@/
  960. id2("t")("o")(to_like);@/
  961. id4("t")("y")("p")("e")(const_like);@/
  962. id5("u")("n")("t")("i")("l")(until_like);@/
  963. id3("v")("a")("r")(var_like);@/
  964. id5("w")("h")("i")("l")("e")(for_like);@/
  965. id4("w")("i")("t")("h")(for_like);@/
  966. id7("x")("c")("l")("a")("u")("s")("e")(loop_like);@/
  967. @* Searching for module names.
  968. The |mod_lookup| procedure finds the module name |mod_text[1..l]| in the
  969. search tree, after inserting it if necessary, and returns a pointer to
  970. where it was found.
  971. @<Glob...@>=
  972. @!mod_text:array [0..longest_name] of ASCII_code; {name being sought for}
  973. @ According to the rules of \.{WEB}, no module name
  974. should be a proper prefix of another, so a ``clean'' comparison should
  975. occur between any two names. The result of |mod_lookup| is 0 if this
  976. prefix condition is violated. An error message is printed when such violations
  977. are detected during phase two of \.{WEAVE}.
  978. @d less=0 {the first name is lexicographically less than the second}
  979. @d equal=1 {the first name is equal to the second}
  980. @d greater=2 {the first name is lexicographically greater than the second}
  981. @d prefix=3 {the first name is a proper prefix of the second}
  982. @d extension=4 {the first name is a proper extension of the second}
  983. @p function mod_lookup(@!l:sixteen_bits):name_pointer; {finds module name}
  984. label found;
  985. var c:less..extension; {comparison between two names}
  986. @!j:0..longest_name; {index into |mod_text|}
  987. @!k:0..max_bytes; {index into |byte_mem|}
  988. @!w:0..ww-1; {row of |byte_mem|}
  989. @!p:name_pointer; {current node of the search tree}
  990. @!q:name_pointer; {father of node |p|}
  991. begin c:=greater; q:=0; p:=root;
  992. while p<>0 do
  993.   begin @<Set variable |c| to the result of comparing the given name
  994.     to name |p|@>;
  995.   q:=p;
  996.   if c=less then p:=llink[q]
  997.   else if c=greater then p:=rlink[q]
  998.   else goto found;
  999.   end;
  1000. @<Enter a new module name into the tree@>;
  1001. found: if c<>equal then
  1002.   begin err_print('! Incompatible section names'); p:=0;
  1003. @.Incompatible section names@>
  1004.   end;
  1005. mod_lookup:=p;
  1006. @ @<Enter a new module name...@>=
  1007. w:=name_ptr mod ww; k:=byte_ptr[w];
  1008. if k+l>max_bytes then overflow('byte memory');
  1009. if name_ptr>max_names-ww then overflow('name');
  1010. p:=name_ptr;
  1011. if c=less then llink[q]:=p else rlink[q]:=p;
  1012. llink[p]:=0; rlink[p]:=0; xref[p]:=0; c:=equal;
  1013. for j:=1 to l do byte_mem[w,k+j-1]:=mod_text[j];
  1014. byte_ptr[w]:=k+l; byte_start[name_ptr+ww]:=k+l; incr(name_ptr);
  1015. @ @<Set variable |c|...@>=
  1016. begin k:=byte_start[p]; w:=p mod ww; c:=equal; j:=1;
  1017. while (k<byte_start[p+ww]) and (j<=l) and (mod_text[j]=byte_mem[w,k]) do
  1018.   begin incr(k); incr(j);
  1019.   end;
  1020. if k=byte_start[p+ww] then
  1021.   if j>l then c:=equal
  1022.   else c:=extension
  1023. else if j>l then c:=prefix
  1024. else if mod_text[j]<byte_mem[w,k] then c:=less
  1025. else c:=greater;
  1026. @ The |prefix_lookup| procedure is supposed to find exactly one module
  1027. name that has |mod_text[1..l]| as a prefix. Actually the algorithm
  1028. silently accepts also the situation that some module name is a prefix of
  1029. |mod_text[1..l]|, because the user who painstakingly typed in more than
  1030. necessary probably doesn't want to be told about the wasted effort.
  1031. Recall that error messages are not printed during phase one. It is
  1032. possible that the |prefix_lookup| procedure will fail on the first pass,
  1033. because there is no match, yet the second pass might detect no error if a
  1034. matching module name has occurred after the offending prefix. In such a
  1035. case the cross-reference information will be incorrect and \.{WEAVE} will
  1036. report no error. However, such a mistake will be detected by the
  1037. \.{TANGLE} processor.
  1038. @p function prefix_lookup(@!l:sixteen_bits):name_pointer; {finds name extension}
  1039. var c:less..extension; {comparison between two names}
  1040. @!count:0..max_names; {the number of hits}
  1041. @!j:0..longest_name; {index into |mod_text|}
  1042. @!k:0..max_bytes; {index into |byte_mem|}
  1043. @!w:0..ww-1; {row of |byte_mem|}
  1044. @!p:name_pointer; {current node of the search tree}
  1045. @!q:name_pointer; {another place to resume the search after one branch is done}
  1046. @!r:name_pointer; {extension found}
  1047. begin q:=0; p:=root; count:=0; r:=0; {begin search at root of tree}
  1048. while p<>0 do
  1049.   begin @<Set variable |c| to the result of comparing...@>;
  1050.   if c=less then p:=llink[p]
  1051.   else if c=greater then p:=rlink[p]
  1052.   else  begin r:=p; incr(count); q:=rlink[p]; p:=llink[p];
  1053.     end;
  1054.   if p=0 then
  1055.     begin p:=q; q:=0;
  1056.     end;
  1057.   end;
  1058. if count<>1 then
  1059.   if count=0 then err_print('! Name does not match')
  1060. @.Name does not match@>
  1061.   else err_print('! Ambiguous prefix');
  1062. @.Ambiguous prefix@>
  1063. prefix_lookup:=r; {the result will be 0 if there was no match}
  1064. @* Lexical scanning.
  1065. Let us now consider the subroutines that read the \.{WEB} source file
  1066. and break it into meaningful units. There are four such procedures:
  1067. One simply skips to the next `\.{@@\ }' or `\.{@@*}' that begins a
  1068. module; another passes over the \TeX\ text at the beginning of a
  1069. module; the third passes over the \TeX\ text in a \PASCAL\ comment;
  1070. and the last, which is the most interesting, gets the next token of
  1071. a \PASCAL\ text.
  1072. @ But first we need to consider the low-level routine |get_line|
  1073. that takes care of merging |change_file| into |web_file|. The |get_line|
  1074. procedure also updates the line numbers for error messages.
  1075. @<Globals...@>=
  1076. @!line:integer; {the number of the current line in the current file}
  1077. @!other_line:integer; {the number of the current line in the input file that
  1078.   is not currently being read}
  1079. @!temp_line:integer; {used when interchanging |line| with |other_line|}
  1080. @!limit:0..long_buf_size; {the last character position occupied in the buffer}
  1081. @!loc:0..long_buf_size; {the next character position to be read from the buffer}
  1082. @!input_has_ended: boolean; {if |true|, there is no more input}
  1083. @!changing: boolean; {if |true|, the current line is from |change_file|}
  1084. @ As we change |changing| from |true| to |false| and back again, we must
  1085. remember to swap the values of |line| and |other_line| so that the |err_print|
  1086. routine will be sure to report the correct line number.
  1087. @d change_changing==
  1088.   changing := not changing;
  1089.   temp_line:=other_line; other_line:=line; line:=temp_line
  1090.     {|line @t$\null\BA\null$@> other_line|}
  1091. @ When |changing| is |false|, the next line of |change_file| is kept in
  1092. |change_buffer[0..change_limit]|, for purposes of comparison with the next
  1093. line of |web_file|. After the change file has been completely input, we
  1094. set |change_limit:=0|, so that no further matches will be made.
  1095. @<Globals...@>=
  1096. @!change_buffer:array[0..buf_size] of ASCII_code;
  1097. @!change_limit:0..buf_size; {the last position occupied in |change_buffer|}
  1098. @ Here's a simple function that checks if the two buffers are different.
  1099. @p function lines_dont_match:boolean;
  1100. label exit;
  1101. var k:0..buf_size; {index into the buffers}
  1102. begin lines_dont_match:=true;
  1103. if change_limit<>limit then return;
  1104. if limit>0 then
  1105.   for k:=0 to limit-1 do if change_buffer[k]<>buffer[k] then return;
  1106. lines_dont_match:=false;
  1107. exit: end;
  1108. @ Procedure |prime_the_change_buffer| sets |change_buffer| in preparation
  1109. for the next matching operation. Since blank lines in the change file are
  1110. not used for matching, we have |(change_limit=0)and not changing| if and
  1111. only if the change file is exhausted. This procedure is called only
  1112. when |changing| is true; hence error messages will be reported correctly.
  1113. @p procedure prime_the_change_buffer;
  1114. label continue, done, exit;
  1115. var k:0..buf_size; {index into the buffers}
  1116. begin change_limit:=0; {this value will be used if the change file ends}
  1117. @<Skip over comment lines in the change file; |return| if end of file@>;
  1118. @<Skip to the next nonblank line; |return| if end of file@>;
  1119. @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>;
  1120. exit: end;
  1121. @ While looking for a line that begins with \.{@@x} in the change file,
  1122. we allow lines that begin with \.{@@}, as long as they don't begin with
  1123. \.{@@y} or \.{@@z} (which would probably indicate that the change file is
  1124. fouled up).
  1125. @<Skip over comment lines in the change file...@>=
  1126. loop@+  begin incr(line);
  1127.   if not input_ln(change_file) then return;
  1128.   if limit<2 then goto continue;
  1129.   if buffer[0]<>"@@" then goto continue;
  1130.   if (buffer[1]>="X")and(buffer[1]<="Z") then
  1131.     buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  1132.   if buffer[1]="x" then goto done;
  1133.   if (buffer[1]="y")or(buffer[1]="z") then
  1134.     begin loc:=2; err_print('! Where is the matching @@x?');
  1135. @.Where is the match...@>
  1136.     end;
  1137. continue: end;
  1138. done:
  1139. @ Here we are looking at lines following the \.{@@x}.
  1140. @<Skip to the next nonblank line...@>=
  1141. repeat incr(line);
  1142.   if not input_ln(change_file) then
  1143.     begin err_print('! Change file ended after @@x');
  1144. @.Change file ended...@>
  1145.     return;
  1146.     end;
  1147. until limit>0;
  1148. @ @<Move |buffer| and |limit| to |change_buffer| and |change_limit|@>=
  1149. begin change_limit:=limit;
  1150. if limit>0 then for k:=0 to limit-1 do change_buffer[k]:=buffer[k];
  1151. @ The following procedure is used to see if the next change entry should
  1152. go into effect; it is called only when |changing| is false.
  1153. The idea is to test whether or not the current
  1154. contents of |buffer| matches the current contents of |change_buffer|.
  1155. If not, there's nothing more to do; but if so, a change is called for:
  1156. All of the text down to the \.{@@y} is supposed to match. An error
  1157. message is issued if any discrepancy is found. Then the procedure
  1158. prepares to read the next line from |change_file|.
  1159. @p procedure check_change; {switches to |change_file| if the buffers match}
  1160. label exit;
  1161. var n:integer; {the number of discrepancies found}
  1162. @!k:0..buf_size; {index into the buffers}
  1163. begin if lines_dont_match then return;
  1164. n:=0;
  1165. loop@+  begin change_changing; {now it's |true|}
  1166.   incr(line);
  1167.   if not input_ln(change_file) then
  1168.     begin err_print('! Change file ended before @@y');
  1169. @.Change file ended...@>
  1170.     change_limit:=0;  change_changing; {|false| again}
  1171.     return;
  1172.     end;
  1173.   @<If the current line starts with \.{@@y},
  1174.     report any discrepancies and |return|@>;
  1175.   @<Move |buffer| and |limit|...@>;
  1176.   change_changing; {now it's |false|}
  1177.   incr(line);
  1178.   if not input_ln(web_file) then
  1179.     begin err_print('! WEB file ended during a change');
  1180. @.WEB file ended...@>
  1181.     input_has_ended:=true; return;
  1182.     end;
  1183.   if lines_dont_match then incr(n);
  1184.   end;
  1185. exit: end;
  1186. @ @<If the current line starts with \.{@@y}...@>=
  1187. if limit>1 then if buffer[0]="@@" then
  1188.   begin if (buffer[1]>="X")and(buffer[1]<="Z") then
  1189.     buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  1190.   if (buffer[1]="x")or(buffer[1]="z") then
  1191.     begin loc:=2; err_print('! Where is the matching @@y?');
  1192. @.Where is the match...@>
  1193.     end
  1194.   else if buffer[1]="y" then
  1195.     begin if n>0 then
  1196.       begin loc:=2; err_print('! Hmm... ',n:1,
  1197.         ' of the preceding lines failed to match');
  1198. @.Hmm... n of the preceding...@>
  1199.       end;
  1200.     return;
  1201.     end;
  1202.   end
  1203. @ The |reset_input| procedure, which gets \.{WEAVE} ready to read the
  1204. user's \.{WEB} input, is used at the beginning of phases one and two.
  1205. @p procedure reset_input;
  1206. begin open_input; line:=0; other_line:=0;@/
  1207. changing:=true; prime_the_change_buffer; change_changing;@/
  1208. limit:=0; loc:=1; buffer[0]:=" "; input_has_ended:=false;
  1209. @ The |get_line| procedure is called when |loc>limit|; it puts the next
  1210. line of merged input into the buffer and updates the other variables
  1211. appropriately. A space is placed at the right end of the line.
  1212. @p procedure get_line; {inputs the next line}
  1213. label restart;
  1214. begin restart: if changing then changed_module[module_count]:=true
  1215. else  @<Read from |web_file| and maybe turn on |changing|@>;
  1216. if changing then
  1217.   begin @<Read from |change_file| and maybe turn off |changing|@>;
  1218.   if not changing then
  1219.     begin changed_module[module_count]:=true; goto restart;
  1220.     end;
  1221.   end;
  1222. loc:=0; buffer[limit]:=" ";
  1223. @ @<Read from |web_file|...@>=
  1224. begin incr(line);
  1225. if not input_ln(web_file) then input_has_ended:=true
  1226. else if limit=change_limit then
  1227.   if buffer[0]=change_buffer[0] then
  1228.     if change_limit>0 then check_change;
  1229. @ @<Read from |change_file|...@>=
  1230. begin incr(line);
  1231. if not input_ln(change_file) then
  1232.   begin err_print('! Change file ended without @@z');
  1233. @.Change file ended...@>
  1234.   buffer[0]:="@@"; buffer[1]:="z"; limit:=2;
  1235.   end;
  1236. if limit>1 then {check if the change has ended}
  1237.   if buffer[0]="@@" then
  1238.     begin if (buffer[1]>="X")and(buffer[1]<="Z") then
  1239.       buffer[1]:=buffer[1]+"z"-"Z"; {lowercasify}
  1240.     if (buffer[1]="x")or(buffer[1]="y") then
  1241.       begin loc:=2; err_print('! Where is the matching @@z?');
  1242. @.Where is the match...@>
  1243.       end
  1244.     else if buffer[1]="z" then
  1245.       begin prime_the_change_buffer; change_changing;
  1246.       end;
  1247.     end;
  1248. @ At the end of the program, we will tell the user if the change file
  1249. had a line that didn't match any relevant line in |web_file|.
  1250. @<Check that all changes have been read@>=
  1251. if change_limit<>0 then {|changing| is false}
  1252.   begin for loc:=0 to change_limit do buffer[loc]:=change_buffer[loc];
  1253.   limit:=change_limit; changing:=true; line:=other_line; loc:=change_limit;
  1254.   err_print('! Change file entry did not match');
  1255. @.Change file entry did not match@>
  1256.   end
  1257. @ Control codes in \.{WEB}, which begin with `\.{@@}', are converted
  1258. into a numeric code designed to simplify \.{WEAVE}'s logic; for example,
  1259. larger numbers are given to the control codes that denote more significant
  1260. milestones, and the code of |new_module| should be the largest of
  1261. all. Some of these numeric control codes take the place of ASCII
  1262. control codes that will not otherwise appear in the output of the
  1263. scanning routines.
  1264. @^ASCII code@>
  1265. @d ignore=0 {control code of no interest to \.{WEAVE}}
  1266. @d verbatim=@'2 {extended ASCII alpha will not appear}
  1267. @d force_line=@'3 {extended ASCII beta will not appear}
  1268. @d begin_comment=@'11 {ASCII tab mark will not appear}
  1269. @d end_comment=@'12 {ASCII line feed will not appear}
  1270. @d octal=@'14 {ASCII form feed will not appear}
  1271. @d hex=@'15 {ASCII carriage return will not appear}
  1272. @d double_dot=@'40 {ASCII space will not appear except in strings}
  1273. @d no_underline=@'175 {this code will be intercepted without confusion}
  1274. @d underline=@'176 {this code will be intercepted without confusion}
  1275. @d param=@'177 {ASCII delete will not appear}
  1276. @d xref_roman=@'203 {control code for `\.{@@\^}'}
  1277. @d xref_wildcard=@'204 {control code for `\.{@@:}'}
  1278. @d xref_typewriter=@'205 {control code for `\.{@@.}'}
  1279. @d TeX_string=@'206 {control code for `\.{@@t}'}
  1280. @d check_sum=@'207 {control code for `\.{@@\$}'}
  1281. @d join=@'210 {control code for `\.{@@\&}'}
  1282. @d thin_space=@'211 {control code for `\.{@@,}'}
  1283. @d math_break=@'212 {control code for `\.{@@\char'174}'}
  1284. @d line_break=@'213 {control code for `\.{@@/}'}
  1285. @d big_line_break=@'214 {control code for `\.{@@\#}'}
  1286. @d no_line_break=@'215 {control code for `\.{@@+}'}
  1287. @d pseudo_semi=@'216 {control code for `\.{@@;}'}
  1288. @d format=@'217 {control code for `\.{@@f}'}
  1289. @d definition=@'220 {control code for `\.{@@d}'}
  1290. @d begin_Pascal=@'221 {control code for `\.{@@p}'}
  1291. @d module_name=@'222 {control code for `\.{@@<}'}
  1292. @d new_module=@'223 {control code for `\.{@@\ }' and `\.{@@*}'}
  1293. @ Control codes are converted from ASCII to \.{WEAVE}'s internal
  1294. representation by the |control_code| routine.
  1295. @p function control_code(@!c:ASCII_code):eight_bits; {convert |c|
  1296.   after \.{@@}}
  1297. begin case c of
  1298. "@@": control_code:="@@"; {`quoted' at sign}
  1299. "'": control_code:=octal; {precedes octal constant}
  1300. """": control_code:=hex; {precedes hexadecimal constant}
  1301. "$": control_code:=check_sum; {precedes check sum constant}
  1302. " ",tab_mark,"*": control_code:=new_module; {beginning of a new module}
  1303. "=": control_code:=verbatim;
  1304. "\": control_code:=force_line;
  1305. "D","d": control_code:=definition; {macro definition}
  1306. "F","f": control_code:=format; {format definition}
  1307. "{": control_code:=begin_comment; {begin-comment delimiter}
  1308. "}": control_code:=end_comment; {end-comment delimiter}
  1309. "P","p": control_code:=begin_Pascal; {\PASCAL\ text in unnamed module}
  1310. "&": control_code:=join; {concatenate two tokens}
  1311. "<": control_code:=module_name; {beginning of a module name}
  1312. ">": begin err_print('! Extra @@>'); control_code:=ignore;
  1313. @.Extra \AT!>@>
  1314.   end; {end of module name should not be discovered in this way}
  1315. "T","t": control_code:=TeX_string; {\TeX\ box within \PASCAL}
  1316. "!": control_code:=underline; {set definition flag}
  1317. "?": control_code:=no_underline; {reset definition flag}
  1318. "^": control_code:=xref_roman; {index entry to be typeset normally}
  1319. ":": control_code:=xref_wildcard; {index entry to be in user format}
  1320. ".": control_code:=xref_typewriter; {index entry to be in typewriter type}
  1321. ",": control_code:=thin_space; {puts extra space in \PASCAL\ format}
  1322. "|": control_code:=math_break; {allows a break in a formula}
  1323. "/": control_code:=line_break; {forces end-of-line in \PASCAL\ format}
  1324. "#": control_code:=big_line_break; {forces end-of-line and some space besides}
  1325. "+": control_code:=no_line_break; {cancels end-of-line down to single space}
  1326. ";": control_code:=pseudo_semi; {acts like a semicolon, but is invisible}
  1327. @t\4@>@<Special control codes allowed only when debugging@>@;
  1328. othercases begin err_print('! Unknown control code'); control_code:=ignore;
  1329. @.Unknown control code@>
  1330.   end
  1331. endcases;
  1332. @ If \.{WEAVE} is compiled with debugging commands, one can write
  1333. \.{@@2}, \.{@@1}, and \.{@@0} to turn tracing fully on, partly on,
  1334. and off, respectively.
  1335. @.\AT!2@>
  1336. @.\AT!1@>
  1337. @<Special control codes...@>=
  1338. @!debug@t@>@/
  1339. "0","1","2": begin tracing:=c-"0"; control_code:=ignore;
  1340.   end;
  1341. gubed
  1342. @ The |skip_limbo| routine is used on the first pass to skip through
  1343. portions of the input that are not in any modules, i.e., that precede
  1344. the first module. After this procedure has been called, the value of
  1345. |input_has_ended| will tell whether or not a new module has
  1346. actually been found.
  1347. @p procedure skip_limbo; {skip to next module}
  1348. label exit;
  1349. var c:ASCII_code; {character following \.{@@}}
  1350. begin loop if loc>limit then
  1351.     begin get_line;
  1352.     if input_has_ended then return;
  1353.     end
  1354.   else  begin buffer[limit+1]:="@@";
  1355.     while buffer[loc]<>"@@" do incr(loc);
  1356.     if loc<=limit then
  1357.       begin loc:=loc+2; c:=buffer[loc-1];
  1358.       if (c=" ")or(c=tab_mark)or(c="*") then return;
  1359.       end;
  1360.     end;
  1361. exit: end;
  1362. @ The |skip_TeX| routine is used on the first pass to skip through
  1363. the \TeX\ code at the beginning of a module. It returns the next
  1364. control code or `\v' found in the input. A |new_module| is
  1365. assumed to exist at the very end of the file.
  1366. @p function skip_TeX: eight_bits; {skip past pure \TeX\ code}
  1367. label done;
  1368. var c:eight_bits; {control code found}
  1369. begin loop begin if loc>limit then
  1370.     begin get_line;
  1371.     if input_has_ended then
  1372.       begin c:=new_module; goto done;
  1373.       end;
  1374.     end;
  1375.   buffer[limit+1]:="@@";
  1376.   repeat c:=buffer[loc]; incr(loc);
  1377.   if c="|" then goto done;
  1378.   until c="@@";
  1379.   if loc<=limit then
  1380.     begin c:=control_code(buffer[loc]); incr(loc); goto done;
  1381.     end;
  1382.   end;
  1383. done:skip_TeX:=c;
  1384. @ The |skip_comment| routine is used on the first pass to skip
  1385. through \TeX\ code in \PASCAL\ comments. The |bal| parameter
  1386. tells how many left braces are assumed to have been scanned when
  1387. this routine is called, and the procedure returns a corresponding
  1388. value of |bal| at the point that scanning has stopped. Scanning
  1389. stops either at a `\v' that introduces \PASCAL\ text,
  1390. in which case the returned value is positive, or it stops at the
  1391. end of the comment, in which case the returned value is zero.
  1392. The scanning also stops in anomalous situations when the comment
  1393. doesn't end or when it contains an illegal use of \.{@@}.
  1394. One should call |skip_comment(1)| when beginning to scan a comment.
  1395. @p function skip_comment(@!bal:eight_bits):eight_bits; {skips \TeX\
  1396.   code in comments}
  1397. label done;
  1398. var c:ASCII_code; {the current character}
  1399. begin loop begin if loc>limit then
  1400.     begin get_line;
  1401.     if input_has_ended then
  1402.       begin bal:=0; goto done;
  1403.       end; {an error message will occur in phase two}
  1404.     end;
  1405.   c:=buffer[loc]; incr(loc);
  1406.   if c="|" then goto done;
  1407.   @<Do special things when |c="@@", "\", "{", "}"|; |goto done| at end@>;
  1408.   end;
  1409. done: skip_comment:=bal;
  1410. @ @<Do special things when |c="@@"...@>=
  1411. if c="@@" then
  1412.   begin c:=buffer[loc];
  1413.   if (c<>" ")and(c<>tab_mark)and(c<>"*") then incr(loc)
  1414.   else  begin decr(loc); bal:=0; goto done;
  1415.     end {an error message will occur in phase two}
  1416.   end
  1417. else if (c="\")and(buffer[loc]<>"@@") then incr(loc)
  1418. else if c="{" then incr(bal)
  1419. else if c="}" then
  1420.   begin decr(bal);
  1421.   if bal=0 then goto done;
  1422.   end
  1423. @* Inputting the next token.
  1424. As stated above, \.{WEAVE}'s most interesting lexical scanning routine is the
  1425. |get_next| function that inputs the next token of \PASCAL\ input. However,
  1426. |get_next| is not especially complicated.
  1427. The result of |get_next| is either an ASCII code for some special character,
  1428. or it is a special code representing a pair of characters (e.g., `\.{:=}'
  1429. or `\.{..}'), or it is the numeric value computed by the |control_code|
  1430. procedure, or it is one of the following special codes:
  1431. \yskip\hang |exponent|: The `\.E' in a real constant.
  1432. \yskip\hang |identifier|: In this case the global variables |id_first|
  1433. and |id_loc| will have been set to the appropriate values needed by the
  1434. |id_lookup| routine.
  1435. \yskip\hang |string|: In this case the global variables |id_first| and
  1436. |id_loc| will have been set to the beginning and ending-plus-one locations
  1437. in the buffer.  The string ends with the first reappearance of its initial
  1438. delimiter; thus, for example, $$\.{\'This isn\'\'t a single string\'}$$
  1439. will be treated as two consecutive strings, the first being \.{\'This
  1440. isn\'}.
  1441. \yskip\noindent Furthermore, some of the control codes cause
  1442. |get_next| to take additional actions:
  1443. \yskip\hang |xref_roman|, |xref_wildcard|,
  1444. |xref_typewriter|, |TeX_string|: The values of
  1445. |id_first| and |id_loc| will be set so that the string in question appears
  1446. in |buffer[id_first..(id_loc-1)]|.
  1447. \yskip\hang |module_name|: In this case the global variable |cur_module| will
  1448. point to the |byte_start| entry for the module name that has just been scanned.
  1449. \yskip\noindent If |get_next| sees `\.{@@!}' or `\.{@@?}',
  1450. it sets |xref_switch| to |def_flag| or zero and goes on to the next token.
  1451. A global variable called |scanning_hex| is set |true| during the time that
  1452. the letters \.A through \.F should be treated as if they were digits.
  1453. @d exponent=@'200 {\.E or \.e following a digit}
  1454. @d string=@'201 {\PASCAL\ string or \.{WEB} precomputed string}
  1455. @d identifier=@'202 {\PASCAL\ identifier or reserved word}
  1456. @<Globals...@>=
  1457. @!cur_module: name_pointer; {name of module just scanned}
  1458. @!scanning_hex: boolean; {are we scanning a hexadecimal constant?}
  1459. @ @<Set init...@>=
  1460. scanning_hex:=false;
  1461. @ As one might expect, |get_next| consists mostly of a big switch
  1462. that branches to the various special cases that can arise.
  1463. @d up_to(#)==#-24,#-23,#-22,#-21,#-20,#-19,#-18,#-17,#-16,#-15,#-14,
  1464.   #-13,#-12,#-11,#-10,#-9,#-8,#-7,#-6,#-5,#-4,#-3,#-2,#-1,#
  1465. @p function get_next:eight_bits; {produces the next input token}
  1466. label restart,done,found;
  1467. var c:eight_bits; {the current character}
  1468. @!d:eight_bits; {the next character}
  1469. @!j,@!k:0..longest_name; {indices into |mod_text|}
  1470. begin restart: if loc>limit then
  1471.   begin get_line;
  1472.   if input_has_ended then
  1473.     begin c:=new_module; goto found;
  1474.     end;
  1475.   end;
  1476. c:=buffer[loc]; incr(loc);
  1477. if scanning_hex then @<Go to |found| if |c| is a hexadecimal digit,
  1478.   otherwise set |scanning_hex:=false|@>;
  1479. case c of
  1480. "A",up_to("Z"),"a",up_to("z"): @<Get an identifier@>;
  1481. "'","""": @<Get a string@>;
  1482. "@@": @<Get control code and possible module name@>;
  1483. @t\4@>@<Compress two-symbol combinations like `\.{:=}'@>@;
  1484. " ",tab_mark: goto restart; {ignore spaces and tabs}
  1485. othercases if c>=128 then goto restart {ignore nonstandard characters}
  1486.   else do_nothing
  1487. endcases;
  1488. found:@!debug if trouble_shooting then debug_help;@;@+gubed@/
  1489. get_next:=c;
  1490. @ @<Go to |found| if |c| is a hexadecimal digit...@>=
  1491. if ((c>="0")and(c<="9"))or((c>="A")and(c<="F")) then goto found
  1492. else scanning_hex:=false
  1493. @ Note that the following code substitutes \.{@@\{} and \.{@@\}} for the
  1494. respective combinations `\.{(*}' and `\.{*)}'. Explicit braces should be used
  1495. for \TeX\ comments in \PASCAL\ text.
  1496. @d compress(#)==begin if loc<=limit then begin c:=#; incr(loc); end; end
  1497. @<Compress two-symbol...@>=
  1498. ".": if buffer[loc]="." then compress(double_dot)
  1499.   else if buffer[loc]=")" then compress("]");
  1500. ":": if buffer[loc]="=" then compress(left_arrow);
  1501. "=": if buffer[loc]="=" then compress(equivalence_sign);
  1502. ">": if buffer[loc]="=" then compress(greater_or_equal);
  1503. "<": if buffer[loc]="=" then compress(less_or_equal)
  1504.   else if buffer[loc]=">" then compress(not_equal);
  1505. "(": if buffer[loc]="*" then compress(begin_comment)
  1506.   else if buffer[loc]="." then compress("[");
  1507. "*": if buffer[loc]=")" then compress(end_comment);
  1508. @ @<Get an identifier@>=
  1509. begin if ((c="E")or(c="e"))and(loc>1) then
  1510.   if (buffer[loc-2]<="9")and(buffer[loc-2]>="0") then c:=exponent;
  1511. if c<>exponent then
  1512.   begin decr(loc); id_first:=loc;
  1513.   repeat incr(loc); d:=buffer[loc];
  1514.   until ((d<"0")or((d>"9")and(d<"A"))or((d>"Z")and(d<"a"))or(d>"z"))and(d<>"_");
  1515.   c:=identifier; id_loc:=loc;
  1516.   end;
  1517. @ A string that starts and ends with single or double quote marks is
  1518. scanned by the following piece of the program.
  1519. @<Get a string@>=
  1520. begin id_first:=loc-1;
  1521. repeat d:=buffer[loc]; incr(loc);
  1522. if loc>limit then
  1523.   begin err_print('! String constant didn''t end');
  1524. @.String constant didn't end@>
  1525.   loc:=limit; d:=c;
  1526.   end;
  1527. until d=c;
  1528. id_loc:=loc; c:=string;
  1529. @ After an \.{@@} sign has been scanned, the next character tells us
  1530. whether there is more work to do.
  1531. @<Get control code and possible module name@>=
  1532. begin c:=control_code(buffer[loc]); incr(loc);
  1533. if c=underline then
  1534.   begin xref_switch:=def_flag; goto restart;
  1535.   end
  1536. else if c=no_underline then
  1537.   begin xref_switch:=0; goto restart;
  1538.   end
  1539. else if (c<=TeX_string)and(c>=xref_roman) then
  1540.   @<Scan to the next \.{@@>}@>
  1541. else if c=hex then scanning_hex:=true
  1542. else if c=module_name then
  1543.   @<Scan the module name and make |cur_module| point to it@>
  1544. else if c=verbatim then @<Scan a verbatim string@>;
  1545. @ The occurrence of a module name sets |xref_switch| to zero,
  1546. because the module name might (for example) follow \&{var}.
  1547. @<Scan the module name...@>=
  1548. begin @<Put module name into |mod_text[1..k]|@>;
  1549. if k>3 then
  1550.   begin if (mod_text[k]=".")and(mod_text[k-1]=".")and(mod_text[k-2]=".") then
  1551.     cur_module:=prefix_lookup(k-3)
  1552.   else cur_module:=mod_lookup(k);
  1553.   end
  1554. else cur_module:=mod_lookup(k);
  1555. xref_switch:=0;
  1556. @ Module names are placed into the |mod_text| array with consecutive spaces,
  1557. tabs, and carriage-returns replaced by single spaces. There will be no
  1558. spaces at the beginning or the end. (We set |mod_text[0]:=" "| to facilitate
  1559. this, since the |mod_lookup| routine uses |mod_text[1]| as the first
  1560. character of the name.)
  1561. @<Set init...@>=mod_text[0]:=" ";
  1562. @ @<Put module name...@>=
  1563. k:=0;
  1564. loop@+  begin if loc>limit then
  1565.     begin get_line;
  1566.     if input_has_ended then
  1567.       begin err_print('! Input ended in section name');
  1568. @.Input ended in section name@>
  1569.       loc:=1; goto done;
  1570.       end;
  1571.     end;
  1572.   d:=buffer[loc];
  1573.   @<If end of name, |goto done|@>;
  1574.   incr(loc); if k<longest_name-1 then incr(k);
  1575.   if (d=" ")or(d=tab_mark) then
  1576.     begin d:=" "; if mod_text[k-1]=" " then decr(k);
  1577.     end;
  1578.   mod_text[k]:=d;
  1579.   end;
  1580. done: @<Check for overlong name@>;
  1581. if (mod_text[k]=" ")and(k>0) then decr(k)
  1582. @ @<If end of name,...@>=
  1583. if d="@@" then
  1584.   begin d:=buffer[loc+1];
  1585.   if d=">" then
  1586.     begin loc:=loc+2; goto done;
  1587.     end;
  1588.   if (d=" ")or(d=tab_mark)or(d="*") then
  1589.     begin err_print('! Section name didn''t end'); goto done;
  1590. @.Section name didn't end@>
  1591.     end;
  1592.   incr(k); mod_text[k]:="@@"; incr(loc); {now |d=buffer[loc]| again}
  1593.   end
  1594. @ @<Check for overlong name@>=
  1595. if k>=longest_name-2 then
  1596.   begin print_nl('! Section name too long: ');
  1597. @.Section name too long@>
  1598.   for j:=1 to 25 do print(xchr[mod_text[j]]);
  1599.   print('...'); mark_harmless;
  1600.   end
  1601. @ @<Scan to the next...@>=
  1602. begin id_first:=loc; buffer[limit+1]:="@@";
  1603. while buffer[loc]<>"@@" do incr(loc);
  1604. id_loc:=loc;
  1605. if loc>limit then
  1606.   begin err_print('! Control text didn''t end'); loc:=limit;
  1607. @.Control text didn't end@>
  1608.   end
  1609. else  begin loc:=loc+2;
  1610.   if buffer[loc-1]<>">" then
  1611.     err_print('! Control codes are forbidden in control text');
  1612. @.Control codes are forbidden...@>
  1613.   end;
  1614. @ A verbatim \PASCAL\ string will be treated like ordinary strings, but
  1615. with no surrounding delimiters.  At the present point in the program we
  1616. have |buffer[loc-1]=verbatim|; we must set |id_first| to the beginning
  1617. of the string itself, and |id_loc| to its ending-plus-one location in the
  1618. buffer.  We also set |loc| to the position just after the ending delimiter.
  1619. @<Scan a verbatim string@>=
  1620. begin id_first:=loc; incr(loc);
  1621. buffer[limit+1]:="@@"; buffer[limit+2]:=">";
  1622. while (buffer[loc]<>"@@")or(buffer[loc+1]<>">") do incr(loc);
  1623. if loc>=limit then err_print('! Verbatim string didn''t end');
  1624. @.Verbatim string didn't end@>
  1625. id_loc:=loc; loc:=loc+2;
  1626. @* Phase one processing.
  1627. We now have accumulated enough subroutines to make it possible to carry out
  1628. \.{WEAVE}'s first pass over the source file. If everything works right,
  1629. both phase one and phase two of \.{WEAVE} will assign the same numbers to
  1630. modules, and these numbers will agree with what \.{TANGLE} does.
  1631. The global variable |next_control| often contains the most recent output of
  1632. |get_next|; in interesting cases, this will be the control code that
  1633. ended a module or part of a module.
  1634. @<Glob...@>=@!next_control:eight_bits; {control code waiting to be acting upon}
  1635. @ The overall processing strategy in phase one has the following
  1636. straightforward outline.
  1637. @<Phase I: Read all the user's text and store the cross references@>=
  1638. phase_one:=true; phase_three:=false;
  1639. reset_input;
  1640. module_count:=0; skip_limbo; change_exists:=false;
  1641. while not input_has_ended do
  1642.   @<Store cross reference data for the current module@>;
  1643. changed_module[module_count]:=change_exists;
  1644.   {the index changes if anything does}
  1645. phase_one:=false; {prepare for second phase}
  1646. @<Print error messages about unused or undefined module names@>;
  1647. @ @<Store cross reference data...@>=
  1648. begin incr(module_count);
  1649. if module_count=max_modules then overflow('section number');
  1650. changed_module[module_count]:=false; {it will become |true| if any line changes}
  1651. if buffer[loc-1]="*" then
  1652.   begin print('*',module_count:1);
  1653.   update_terminal; {print a progress report}
  1654.   end;
  1655. @<Store cross references in the \TeX\ part of a module@>;
  1656. @<Store cross references in the \(definition part of a module@>;
  1657. @<Store cross references in the \PASCAL\ part of a module@>;
  1658. if changed_module[module_count] then change_exists:=true;
  1659. @ The |Pascal_xref| subroutine stores references to identifiers in
  1660. \PASCAL\ text material beginning with the current value of |next_control|
  1661. and continuing until |next_control| is `\.\{' or `\v', or until the next
  1662. ``milestone'' is passed (i.e., |next_control>=format|). If
  1663. |next_control>=format| when |Pascal_xref| is called, nothing will happen;
  1664. but if |next_control="|"| upon entry, the procedure assumes that this is
  1665. the `\v' preceding \PASCAL\ text that is to be processed.
  1666. The program uses the fact that our internal code numbers satisfy
  1667. the relations |xref_roman=identifier+roman| and |xref_wildcard=identifier
  1668. +wildcard| and |xref_typewriter=identifier+
  1669. typewriter| and |normal=0|. An implied `\.{@@!}' is inserted after
  1670. \&{function}, \&{procedure}, \&{program}, and \&{var}.
  1671. @p procedure Pascal_xref; {makes cross references for \PASCAL\ identifiers}
  1672. label exit;
  1673. var p:name_pointer; {a referenced name}
  1674. begin while next_control<format do
  1675.   begin if (next_control>=identifier)and
  1676.       (next_control<=xref_typewriter) then
  1677.     begin p:=id_lookup(next_control-identifier); new_xref(p);
  1678.     if (ilk[p]=proc_like)or(ilk[p]=var_like) then
  1679.       xref_switch:=def_flag; {implied `\.{@@!}'}
  1680.     end;
  1681.   next_control:=get_next;
  1682.   if (next_control="|")or(next_control="{") then return;
  1683.   end;
  1684. exit:end;
  1685. @ The |outer_xref| subroutine is like |Pascal_xref| but it begins
  1686. with |next_control<>"|"| and ends with |next_control>=format|. Thus, it
  1687. handles \PASCAL\ text with embedded comments.
  1688. @p procedure outer_xref; {extension of |Pascal_xref|}
  1689. var bal:eight_bits; {brace level in comment}
  1690. begin while next_control<format do
  1691.   if next_control<>"{" then Pascal_xref
  1692.   else  begin bal:=skip_comment(1); next_control:="|";
  1693.     while bal>0 do
  1694.       begin Pascal_xref;
  1695.       if next_control="|" then bal:=skip_comment(bal)
  1696.       else bal:=0; {an error will be reported in phase two}
  1697.       end;
  1698.     end;
  1699. @ In the \TeX\ part of a module, cross reference entries are made only for
  1700. the identifiers in \PASCAL\ texts enclosed in \pb, or for control texts
  1701. enclosed in \.{@@\^}$\,\ldots\,$\.{@@>} or \.{@@.}$\,\ldots\,$\.{@@>}
  1702. or \.{@@:}$\,\ldots\,$\.{@@>}.
  1703. @<Store cross references in the \T...@>=
  1704. repeat next_control:=skip_TeX;
  1705. case next_control of
  1706. underline: xref_switch:=def_flag;
  1707. no_underline: xref_switch:=0;
  1708. "|": Pascal_xref;
  1709. xref_roman, xref_wildcard, xref_typewriter, module_name:
  1710.   begin loc:=loc-2; next_control:=get_next; {scan to \.{@@>}}
  1711.   if next_control<>module_name then
  1712.     new_xref(id_lookup(next_control-identifier));
  1713.   end;
  1714. othercases do_nothing
  1715. endcases;
  1716. until next_control>=format
  1717. @ During the definition and \PASCAL\ parts of a module, cross references
  1718. are made for all identifiers except reserved words; however, the
  1719. identifiers in a format definition are referenced even if they are
  1720. reserved. The \TeX\ code in comments is, of course, ignored, except for
  1721. \PASCAL\ portions enclosed in \pb; the text of a module name is skipped
  1722. entirely, even if it contains \pb\ constructions.
  1723. The variables |lhs| and |rhs| point to the respective identifiers involved
  1724. in a format definition.
  1725. @<Global...@>=
  1726. @!lhs,@!rhs:name_pointer; {indices into |byte_start| for format identifiers}
  1727. @ When we get to the following code we have |next_control>=format|.
  1728. @<Store cross references in the \(d...@>=
  1729. while next_control<=definition do {|format| or |definition|}
  1730.   begin xref_switch:=def_flag; {implied \.{@@!}}
  1731.   if next_control=definition then next_control:=get_next
  1732.   else @<Process a format definition@>;
  1733.   outer_xref;
  1734.   end
  1735. @ Error messages for improper format definitions will be issued in phase
  1736. two. Our job in phase one is to define the |ilk| of a properly formatted
  1737. identifier, and to fool the |new_xref| routine into thinking that the
  1738. identifier on the right-hand side of the format definition is not a
  1739. reserved word.
  1740. @<Process a form...@>=
  1741. begin next_control:=get_next;
  1742. if next_control=identifier then
  1743.   begin lhs:=id_lookup(normal); ilk[lhs]:=normal; new_xref(lhs);
  1744.   next_control:=get_next;
  1745.   if next_control=equivalence_sign then
  1746.     begin next_control:=get_next;
  1747.     if next_control=identifier then
  1748.       begin rhs:=id_lookup(normal);
  1749.       ilk[lhs]:=ilk[rhs]; ilk[rhs]:=normal; new_xref(rhs);
  1750.       ilk[rhs]:=ilk[lhs]; next_control:=get_next;
  1751.       end;
  1752.     end;
  1753.   end;
  1754. @ Finally, when the \TeX\ and definition parts have been treated, we have
  1755. |next_control>=begin_Pascal|.
  1756. @<Store cross references in the \P...@>=
  1757. if next_control<=module_name then {|begin_Pascal| or |module_name|}
  1758.   begin if next_control=begin_Pascal then mod_xref_switch:=0
  1759.   else mod_xref_switch:=def_flag;
  1760.   repeat if next_control=module_name then new_mod_xref(cur_module);
  1761.     next_control:=get_next; outer_xref;
  1762.   until next_control>module_name;
  1763.   end
  1764. @ After phase one has looked at everything, we want to check that each
  1765. module name was both defined and used.
  1766. The variable |cur_xref| will point to cross references for the
  1767. current module name of interest.
  1768. @<Glob...@>=@!cur_xref:xref_number; {temporary cross reference pointer}
  1769. @ The following recursive procedure
  1770. walks through the tree of module names and prints out anomalies.
  1771. @^recursion@>
  1772. @p procedure mod_check(@!p:name_pointer); {print anomalies in subtree |p|}
  1773. begin if p>0 then
  1774.   begin mod_check(llink[p]);@/
  1775.   cur_xref:=xref[p];
  1776.   if num(cur_xref)<def_flag then
  1777.     begin print_nl('! Never defined: <'); print_id(p);
  1778. @.Never defined: <section name>@>
  1779.     print('>'); mark_harmless;
  1780.     end;
  1781.   while num(cur_xref)>=def_flag do cur_xref:=xlink(cur_xref);
  1782.   if cur_xref=0 then
  1783.     begin print_nl('! Never used: <'); print_id(p); print('>');
  1784. @.Never used: <section name>@>
  1785.     mark_harmless;
  1786.     end;
  1787.   mod_check(rlink[p]);
  1788.   end;
  1789. @ @<Print error messages about un...@>=@+mod_check(root)
  1790. @* Low-level output routines.
  1791. The \TeX\ output is supposed to appear in lines at most |line_length|
  1792. characters long, so we place it into an output buffer. During the output
  1793. process, |out_line| will hold the current line number of the line about to
  1794. be output.
  1795. @<Glo...@>=
  1796. @!out_buf:array[0..line_length] of ASCII_code; {assembled characters}
  1797. @!out_ptr:0..line_length; {number of characters in |out_buf|}
  1798. @!out_line: integer; {coordinates of next line to be output}
  1799. @ The |flush_buffer| routine empties the buffer up to a given breakpoint,
  1800. and moves any remaining characters to the beginning of the next line.
  1801. If the |per_cent| parameter is |true|, a |"%"| is appended to the line
  1802. that is being output; in this case the breakpoint |b| should be strictly
  1803. less than |line_length|. If the |per_cent| parameter is |false|,
  1804. trailing blanks are suppressed.
  1805. The characters emptied from the buffer form a new line of output.
  1806. @p procedure flush_buffer(@!b:eight_bits;@!per_cent:boolean);
  1807.   {outputs |out_buf[1..b]|, where |b<=out_ptr|}
  1808. label done;
  1809. var j,@!k:0..line_length;
  1810. begin j:=b;
  1811. if not per_cent then {remove trailing blanks}
  1812.   loop@+  begin if j=0 then goto done;
  1813.     if out_buf[j]<>" " then goto done;
  1814.     decr(j);
  1815.     end;
  1816. done: for k:=1 to j do write(tex_file,xchr[out_buf[k]]);
  1817. if per_cent then write(tex_file,xchr["%"]);
  1818. write_ln(tex_file); incr(out_line);
  1819. if b<out_ptr then for k:=b+1 to out_ptr do out_buf[k-b]:=out_buf[k];
  1820. out_ptr:=out_ptr-b;
  1821. @ When we are copying \TeX\ source material, we retain line breaks
  1822. that occur in the input, except that an empty line is not
  1823. output when the \TeX\ source line was nonempty. For example, a line
  1824. of the \TeX\ file that contains only an index cross-reference entry
  1825. will not be copied. The |finish_line| routine is called just before
  1826. |get_line| inputs a new line, and just after a line break token has
  1827. been emitted during the output of translated \PASCAL\ text.
  1828. @p procedure finish_line; {do this at the end of a line}
  1829. label exit;
  1830. var k:0..buf_size; {index into |buffer|}
  1831. begin if out_ptr>0 then flush_buffer(out_ptr,false)
  1832. else  begin for k:=0 to limit do
  1833.     if (buffer[k]<>" ")and(buffer[k]<>tab_mark) then return;
  1834.   flush_buffer(0,false);
  1835.   end;
  1836. exit:end;
  1837. @ In particular, the |finish_line| procedure is called near the very
  1838. beginning of phase two. We initialize the output variables in a slightly
  1839. tricky way so that the first line of the output file will be
  1840. `\.{\\input webmac}'.
  1841. @.\\input webmac@>
  1842. @.webmac@>
  1843. @<Set init...@>=
  1844. out_ptr:=1; out_line:=1; out_buf[1]:="c"; write(tex_file,'\input webma');
  1845. @ When we wish to append the character |c| to the output buffer, we write
  1846. `$|out|(c)$'; this will cause the buffer to be emptied if it was already
  1847. full. Similarly, `$|out2|(c_1)(c_2)$' appends a pair of characters.
  1848. A line break will occur at a space or after a single-nonletter
  1849. \TeX\ control sequence.
  1850. @d oot(#)==@;@/
  1851.   if out_ptr=line_length then break_out;
  1852.   incr(out_ptr); out_buf[out_ptr]:=#;
  1853. @d oot1(#)==oot(#)@+end
  1854. @d oot2(#)==oot(#)@,oot1
  1855. @d oot3(#)==oot(#)@,oot2
  1856. @d oot4(#)==oot(#)@,oot3
  1857. @d oot5(#)==oot(#)@,oot4
  1858. @d out==@+begin oot1
  1859. @d out2==@+begin oot2
  1860. @d out3==@+begin oot3
  1861. @d out4==@+begin oot4
  1862. @d out5==@+begin oot5
  1863. @ The |break_out| routine is called just before the output buffer is about
  1864. to overflow. To make this routine a little faster, we initialize position
  1865. 0 of the output buffer to `\.\\'; this character isn't really output.
  1866. @<Set init...@>=
  1867. out_buf[0]:="\";
  1868. @ A long line is broken at a blank space or just before a backslash that isn't
  1869. preceded by another backslash. In the latter case, a |"%"| is output at
  1870. the break.
  1871. @p procedure break_out; {finds a way to break the output line}
  1872. label exit;
  1873. var k:0..line_length; {index into |out_buf|}
  1874. @!c,@!d:ASCII_code; {characters from the buffer}
  1875. begin k:=out_ptr;
  1876. loop@+  begin if k=0 then
  1877.     @<Print warning message, break the line, |return|@>;
  1878.   d:=out_buf[k];
  1879.   if d=" " then
  1880.     begin flush_buffer(k,false); return;
  1881.     end;
  1882.   if (d="\")and(out_buf[k-1]<>"\") then {in this case |k>1|}
  1883.     begin flush_buffer(k-1,true); return;
  1884.     end;
  1885.   decr(k);
  1886.   end;
  1887. exit:end;
  1888. @ We get to this module only in unusual cases that the entire output line
  1889. consists of a string of backslashes followed by a string of nonblank
  1890. non-backslashes. In such cases it is almost always safe to break the
  1891. line by putting a |"%"| just before the last character.
  1892. @<Print warning message...@>=
  1893. begin print_nl('! Line had to be broken (output l.',out_line:1);
  1894. @.Line had to be broken@>
  1895. print_ln('):');
  1896. for k:=1 to out_ptr-1 do print(xchr[out_buf[k]]);
  1897. new_line; mark_harmless;
  1898. flush_buffer(out_ptr-1,true); return;
  1899. @ Here is a procedure that outputs a module number in decimal notation.
  1900. @<Glob...@>=@!dig:array[0..4] of 0..9; {digits to output}
  1901. @ The number to be converted by |out_mod| is known to be less than
  1902. |def_flag|, so it cannot have more than five decimal digits.  If
  1903. the module is changed, we output `\.{\\*}' just after the number.
  1904. @p procedure out_mod(@!m:integer); {output a module number}
  1905. var k:0..5; {index into |dig|}
  1906. @!a:integer; {accumulator}
  1907. begin k:=0; a:=m;
  1908. repeat dig[k]:=a mod 10; a:=a div 10; incr(k);
  1909. until a=0;
  1910. repeat decr(k); out(dig[k]+"0");
  1911. until k=0;
  1912. if changed_module[m] then out2("\")("*");
  1913. @.\\*@>
  1914. @ The |out_name| subroutine is used to output an identifier or index
  1915. entry, enclosing it in braces.
  1916. @p procedure out_name(@!p:name_pointer); {outputs a name}
  1917. var k:0..max_bytes; {index into |byte_mem|}
  1918. @!w:0..ww-1; {row of |byte_mem|}
  1919. begin out("{"); w:=p mod ww;
  1920. for k:=byte_start[p] to byte_start[p+ww]-1 do
  1921.   begin if byte_mem[w,k]="_" then out("\");
  1922. @.\\_@>
  1923.   out(byte_mem[w,k]);
  1924.   end;
  1925. out("}");
  1926. @* Routines that copy \TeX\ material.
  1927. During phase two, we use the subroutines |copy_limbo|, |copy_TeX|, and
  1928. |copy_comment| in place of the analogous |skip_limbo|, |skip_TeX|, and
  1929. |skip_comment| that were used in phase one.
  1930. The |copy_limbo| routine, for example, takes \TeX\ material that is not
  1931. part of any module and transcribes it almost verbatim to the output file.
  1932. No `\.{@@}' signs should occur in such material except in `\.{@@@@}'
  1933. pairs; such pairs are replaced by singletons.
  1934. @p procedure copy_limbo; {copy \TeX\ code until the next module begins}
  1935. label exit;
  1936. var c:ASCII_code; {character following \.{@@} sign}
  1937. begin loop if loc>limit then
  1938.     begin finish_line; get_line;
  1939.     if input_has_ended then return;
  1940.     end
  1941.   else  begin buffer[limit+1]:="@@";
  1942.     @<Copy up to control code, |return| if finished@>;
  1943.     end;
  1944. exit:end;
  1945. @ @<Copy up to control...@>=
  1946. while buffer[loc]<>"@@" do
  1947.   begin out(buffer[loc]); incr(loc);
  1948.   end;
  1949. if loc<=limit then
  1950.   begin loc:=loc+2; c:=buffer[loc-1];
  1951.   if (c=" ")or(c=tab_mark)or(c="*") then return;
  1952.   if (c<>"z")and(c<>"Z") then
  1953.     begin out("@@");
  1954.     if c<>"@@" then err_print('! Double @@ required outside of sections');
  1955. @.Double \AT! required...@>
  1956.     end;
  1957.   end
  1958. @ The |copy_TeX| routine processes the \TeX\ code at the beginning of a
  1959. module; for example, the words you are now reading were copied in this
  1960. way. It returns the next control code or `\v' found in the input.
  1961. @p function copy_TeX:eight_bits; {copy pure \TeX\ material}
  1962. label done;
  1963. var c:eight_bits; {control code found}
  1964. begin loop begin if loc>limit then
  1965.     begin finish_line; get_line;
  1966.     if input_has_ended then
  1967.       begin c:=new_module; goto done;
  1968.       end;
  1969.     end;
  1970.   buffer[limit+1]:="@@";
  1971.   @<Copy up to `\v' or control code, |goto done| if finished@>;
  1972.   end;
  1973. done:copy_TeX:=c;
  1974. @ We don't copy spaces or tab marks into the beginning of a line. This
  1975. makes the test for empty lines in |finish_line| work.
  1976. @<Copy up to `\v'...@>=
  1977. repeat c:=buffer[loc]; incr(loc);
  1978. if c="|" then goto done;
  1979. if c<>"@@" then
  1980.   begin out(c);
  1981.   if (out_ptr=1)and((c=" ")or(c=tab_mark)) then decr(out_ptr);
  1982.   end;
  1983. until c="@@";
  1984. if loc<=limit then
  1985.   begin c:=control_code(buffer[loc]); incr(loc);
  1986.   goto done;
  1987.   end
  1988. @ The |copy_comment| uses and returns a brace-balance value, following the
  1989. conventions of |skip_comment| above. Instead of copying the \TeX\ material
  1990. into the output buffer, this procedure copies it into the token memory.
  1991. The abbreviation |app_tok(t)| is used to append token |t| to the current
  1992. token list, and it also makes sure that it is possible to append at least
  1993. one further token without overflow.
  1994. @d app_tok(#)==begin if tok_ptr+2>max_toks then overflow('token');
  1995.   tok_mem[tok_ptr]:=#; incr(tok_ptr);
  1996.   end
  1997. @p function copy_comment(@!bal:eight_bits):eight_bits; {copies \TeX\ code in
  1998.   comments}
  1999. label done;
  2000. var c:ASCII_code; {current character being copied}
  2001. begin loop begin if loc>limit then
  2002.     begin get_line;
  2003.     if input_has_ended then
  2004.       begin err_print('! Input ended in mid-comment');
  2005. @.Input ended in mid-comment@>
  2006.       loc:=1; @<Clear |bal| and |goto done|@>;
  2007.       end;
  2008.     end;
  2009.   c:=buffer[loc]; incr(loc);
  2010.   if c="|" then goto done;
  2011.   app_tok(c);
  2012.   @<Copy special things when |c="@@", "\", "{", "}"|;
  2013.     |goto done| at end@>;
  2014.   end;
  2015. done: copy_comment:=bal;
  2016. @ @<Copy special things when |c="@@"...@>=
  2017. if c="@@" then
  2018.   begin incr(loc);
  2019.   if buffer[loc-1]<>"@@" then
  2020.     begin err_print('! Illegal use of @@ in comment');
  2021. @.Illegal use of \AT!...@>
  2022.     loc:=loc-2; decr(tok_ptr); @<Clear |bal|...@>;
  2023.     end;
  2024.   end
  2025. else if (c="\")and(buffer[loc]<>"@@") then
  2026.   begin app_tok(buffer[loc]); incr(loc);
  2027.   end
  2028. else if c="{" then incr(bal)
  2029. else if c="}" then
  2030.   begin decr(bal);
  2031.   if bal=0 then goto done;
  2032.   end
  2033. @ When the comment has terminated abruptly due to an error, we output
  2034. enough right braces to keep \TeX\ happy.
  2035. @<Clear |bal|...@>=
  2036. app_tok(" "); {this is done in case the previous character was `\.\\'}
  2037. repeat app_tok("}"); decr(bal);
  2038. until bal=0;
  2039. goto done;
  2040. @* Parsing.
  2041. The most intricate part of \.{WEAVE} is its mechanism for converting
  2042. \PASCAL-like code into \TeX\ code, and we might as well plunge into this
  2043. aspect of the program now. A ``bottom up'' approach is used to parse the
  2044. \PASCAL-like material, since \.{WEAVE} must deal with fragmentary
  2045. constructions whose overall ``part of speech'' is not known.
  2046. At the lowest level, the input is represented as a sequence of entities
  2047. that we shall call {\it scraps}, where each scrap of information consists
  2048. of two parts, its {\it category} and its {\it translation}. The category
  2049. is essentially a syntactic class, and the translation is a token list that
  2050. represents \TeX\ code. Rules of syntax and semantics tell us how to
  2051. combine adjacent scraps into larger ones, and if we are lucky an entire
  2052. \PASCAL\ text that starts out as hundreds of small scraps will join
  2053. together into one gigantic scrap whose translation is the desired \TeX\
  2054. code. If we are unlucky, we will be left with several scraps that don't
  2055. combine; their translations will simply be output, one by one.
  2056. The combination rules are given as context-sensitive productions that are
  2057. applied from left to right. Suppose that we are currently working on the
  2058. sequence of scraps $s_1\,s_2\ldots s_n$. We try first to find the longest
  2059. production that applies to an initial substring $s_1\,s_2\ldots\,$; but if
  2060. no such productions exist, we find to find the longest production
  2061. applicable to the next substring $s_2\,s_3\ldots\,$; and if that fails, we
  2062. try to match $s_3\,s_4\ldots\,$, etc.
  2063. A production applies if the category codes have a given pattern. For
  2064. example, one of the productions is
  2065. $$|open|\;|math|\;|semi|\;\RA\;|open|\;|math|$$
  2066. and it means that three consecutive scraps whose respective categories are
  2067. |open|, |math|, and |semi| are con\-verted to two scraps whose categories
  2068. are |open| and |math|. This production also has an associated rule that
  2069. tells how to combine the translation parts:
  2070. $$\eqalign{O_2&=O_1\cr
  2071. M_2&=M_1\,S\,\.{\\,}\,\hbox{|opt|\thinspace\tt5}\cr}$$
  2072. This means that the |open| scrap has not changed, while the new |math| scrap
  2073. has a translation $M_2$ composed of the translation $M_1$ of the original
  2074. |math| scrap followed by the translation |S| of the |semi| scrap followed
  2075. by `\.{\\,}' followed by `|opt|' followed by `\.5'. (In the \TeX\ file,
  2076. this will specify an additional thin space after the semicolon, followed
  2077. by an optional line break with penalty 50.) Translation rules use subscripts
  2078. to distinguish between translations of scraps whose categories have the
  2079. same initial letter; these subscripts are assigned from left to right.
  2080. $\.{WEAVE}$ also has the production rule
  2081. $$|semi|\;\RA\;|terminator|$$
  2082. (meaning that a semicolon can terminate a \PASCAL\ statement). Since
  2083. productions are applied from left to right, this rule will be activated
  2084. only if the |semi| is not preceded by scraps that match other productions;
  2085. in particular, a |semi| that is preceded by `|open| |math|' will have
  2086. disappeared because of the production above, and such semicolons do not
  2087. act as statement terminators.  This incidentally is how \.{WEAVE} is able
  2088. to treat semicolons in two distinctly different ways, the first of which
  2089. is intended for semicolons in the parameter list of a procedure
  2090. declaration.
  2091. The translation rule corresponding to $|semi|\;\RA\;|terminator|$ is
  2092. $$T=S$$
  2093. but we shall not mention translation rules in the common case that the
  2094. translation of the new scrap on the right-hand side is simply the
  2095. concatenation of the disappearing scraps on the left-hand side.
  2096. @ Here is a list of the category codes that scraps can have.
  2097. @d simp=1 {the translation can be used both in horizontal mode
  2098.   and in math mode of \TeX}
  2099. @d math=2 {the translation should be used only in \TeX\ math mode}
  2100. @d intro=3 {a statement is expected to follow this, after a space and
  2101.   an optional break}
  2102. @d open=4 {denotes an incomplete parenthesized quantity to be used in
  2103.   math mode}
  2104. @d beginning=5 {denotes an incomplete compound statement to be used in
  2105.   horizontal mode}
  2106. @d close=6 {ends a parenthesis or compound statement}
  2107. @d alpha=7 {denotes the beginning of a clause}
  2108. @d omega=8 {denotes the ending of a clause and possible comment following}
  2109. @d semi=9 {denotes a semicolon and possible comment following it}
  2110. @d terminator=10 {something that ends a statement or declaration}
  2111. @d stmt=11 {denotes a statement or declaration including its terminator}
  2112. @d cond=12 {precedes an \&{if} clause that might have a matching \&{else}}
  2113. @d clause=13 {precedes a statement after which indentation ends}
  2114. @d colon=14 {denotes a colon}
  2115. @d exp=15 {stands for the E in a floating point constant}
  2116. @d proc=16 {denotes a procedure or program or function heading}
  2117. @d case_head=17 {denotes a case statement or record heading}
  2118. @d record_head=18 {denotes a record heading without indentation}
  2119. @d var_head=19 {denotes a variable declaration heading}
  2120. @d elsie=20 {\&{else}}
  2121. @d casey=21 {\&{case}}
  2122. @d mod_scrap=22 {denotes a module name}
  2123. @p @!debug procedure print_cat(@!c:eight_bits);
  2124.   {symbolic printout of a category}
  2125. begin case c of
  2126. simp: print('simp');
  2127. math: print('math');
  2128. intro: print('intro');
  2129. open: print('open');
  2130. beginning: print('beginning');
  2131. close: print('close');
  2132. alpha: print('alpha');
  2133. omega: print('omega');
  2134. semi: print('semi');
  2135. terminator: print('terminator');
  2136. stmt: print('stmt');
  2137. cond: print('cond');
  2138. clause: print('clause');
  2139. colon: print('colon');
  2140. exp: print('exp');
  2141. proc: print('proc');
  2142. case_head: print('casehead');
  2143. record_head: print('recordhead');
  2144. var_head: print('varhead');
  2145. elsie: print('elsie');
  2146. casey: print('casey');
  2147. mod_scrap: print('module');
  2148. othercases print('UNKNOWN')
  2149. endcases;
  2150. gubed
  2151. @ The token lists for translated \TeX\ output contain some special control
  2152. symbols as well as ordinary characters. These control symbols are
  2153. interpreted by \.{WEAVE} before they are written to the output file.
  2154. \yskip\hang |break_space| denotes an optional line break or an en space;
  2155. \yskip\hang |force| denotes a line break;
  2156. \yskip\hang |big_force| denotes a line break with additional vertical space;
  2157. \yskip\hang |opt| denotes an optional line break (with the continuation
  2158. line indented two ems with respect to the normal starting position)---this
  2159. code is followed by an integer |n|, and the break will occur with penalty
  2160. $10n$;
  2161. \yskip\hang |backup| denotes a backspace of one em;
  2162. \yskip\hang |cancel| obliterates any |break_space| or |force| or |big_force|
  2163. tokens that immediately precede or follow it and also cancels any
  2164. |backup| tokens that follow it;
  2165. \yskip\hang |indent| causes future lines to be indented one more em;
  2166. \yskip\hang |outdent| causes future lines to be indented one less em.
  2167. \yskip\noindent All of these tokens are removed from the \TeX\ output that
  2168. comes from \PASCAL\ text between \pb\ signs; |break_space| and |force| and
  2169. |big_force| become single spaces in this mode. The translation of other
  2170. \PASCAL\ texts results in \TeX\ control sequences \.{\\1}, \.{\\2},
  2171. \.{\\3}, \.{\\4}, \.{\\5}, \.{\\6}, \.{\\7} corresponding respectively to
  2172. |indent|, |outdent|, |opt|, |backup|, |break_space|, |force|, and
  2173. |big_force|. However, a sequence of consecutive `\.\ ', |break_space|,
  2174. |force|, and/or |big_force| tokens is first replaced by a single token
  2175. (the maximum of the given ones).
  2176. The tokens |math_rel|, |math_bin|, |math_op| will be translated into
  2177. \.{\\mathrel\{}, \.{\\mathbin\{}, and \.{\\mathop\{}, respectively.
  2178. Other control sequences in the \TeX\ output will be `\.{\\\\\{}$\,\ldots\,$\.\}'
  2179. surrounding identifiers, `\.{\\\&\{}$\,\ldots\,$\.\}' surrounding
  2180. reserved words, `\.{\\.\{}$\,\ldots\,$\.\}' surrounding strings,
  2181. `\.{\\C\{}$\,\ldots\,$\.\}$\,$|force|' surrounding comments, and
  2182. `\.{\\X$n$:}$\,\ldots\,$\.{\\X}' surrounding module names, where
  2183. |n| is the module number.
  2184. @d math_bin=@'203
  2185. @d math_rel=@'204
  2186. @d math_op=@'205
  2187. @d big_cancel=@'206 {like |cancel|, also overrides spaces}
  2188. @d cancel=@'207 {overrides |backup|, |break_space|, |force|, |big_force|}
  2189. @d indent=cancel+1 {one more tab (\.{\\1})}
  2190. @d outdent=cancel+2 {one less tab (\.{\\2})}
  2191. @d opt=cancel+3 {optional break in mid-statement (\.{\\3})}
  2192. @d backup=cancel+4 {stick out one unit to the left (\.{\\4})}
  2193. @d break_space=cancel+5 {optional break between statements (\.{\\5})}
  2194. @d force=cancel+6 {forced break between statements (\.{\\6})}
  2195. @d big_force=cancel+7 {forced break with additional space (\.{\\7})}
  2196. @d end_translation=big_force+1 {special sentinel token at end of list}
  2197. @ The raw input is converted into scraps according to the following table,
  2198. which gives category codes followed by the translations. Sometimes a single
  2199. item of input produces more than one scrap.
  2200. \def\stars {\.{**}}%
  2201. (The symbol `\stars' stands for `\.{\\\&\{{\rm identifier}\}}',
  2202. i.e., the identifier itself treated as a reserved word. In a few cases the
  2203. category is given as `|@!comment|'; this is not an actual category code, it
  2204. means that the translation will be treated as a comment, as explained
  2205. below.)
  2206. \yskip\halign{\quad#\hfil&\quad#\hfil\cr
  2207. \.{<>}&|math:|\.{\\I}\cr
  2208. \.{<=}&|math:|\.{\\L}\cr
  2209. \.{>=}&|math:|\.{\\G}\cr
  2210. \.{:=}&|math:|\.{\\K}\cr
  2211. \.{==}&|math:|\.{\\S}\cr
  2212. \.{(*}&|math:|\.{\\B}\cr
  2213. \.{*)}&|math:|\.{\\T}\cr
  2214. \.{(.}&|open:|\.[\cr
  2215. \.{.)}&|close:|\.]\cr
  2216. \."$\,$string$\,$\."&|simp:|\.{\\.\{"{\rm$\,$modified string$\,$}"\}}\cr
  2217. \.\'$\,$string$\,$\.\'&|simp:|\.{\\.\{\\\'{\rm$\,$modified
  2218.   string$\,$}\\\'\}}\cr
  2219. \.{@@=}$\,$string$\,$\.{@@>}&|simp:|\.{\\=\{{\rm$\,$modified string$\,$}\}}\cr
  2220. \#&|math:|\.{\\\#}\cr
  2221. \.\$&|math:|\.{\\\$}\cr
  2222. \.\_&|math:|\.{\\\_}\cr
  2223. \.\%&|math:|\.{\\\%}\cr
  2224. \.\^&|math:|\.{\\\^}\cr
  2225. \.(&|open:|\.(\cr
  2226. \.)&|close:|\.)\cr
  2227. \.[&|open:|\.[\cr
  2228. \.]&|close:|\.]\cr
  2229. \.*&|math:|\.{\\ast}\cr
  2230. \.,&|math:|\.,|@,opt@,|\.9\cr
  2231. \.{..}&|math:|\.{\\to}\cr
  2232. \..&|simp:|\..\cr
  2233. \.:&|colon:|\.:\cr
  2234. \.;&|semi:|\.;\cr
  2235. identifier&|simp:|\.{\\\\\{{\rm$\,$identifier$\,$}\}}\cr
  2236. \.E in constant&|exp:|\.{\\E\{}\cr
  2237. digit $d$&|simp:|$d$\cr
  2238. other character $c$&|math:|$c$\cr
  2239. \.{and}&|math:|\.{\\W}\cr
  2240. \.{array}&|alpha:|\stars\cr
  2241. \.{begin}&|beginning:|$|force|\,\stars\,|cancel|$\qquad|intro:|\cr
  2242. \.{case}&|casey:|\qquad|alpha:|$|force|\,\stars$\cr
  2243. \.{const}&|intro:|$|force|\,|backup|\,\stars$\cr
  2244. \.{div}&|math:|$|math_bin|\,\stars\,\.\}$\cr
  2245. \.{do}&|omega:|\stars\cr
  2246. \.{downto}&|math:|$|math_rel|\,\stars\,\.\}$\cr
  2247. \.{else}&|terminator:|\qquad|elsie:|$|force|\,|backup|\,\stars$\cr
  2248. \.{end}&|terminator:|\qquad|close:|$|force|\,\stars$\cr
  2249. \.{file}&|alpha:|\stars\cr
  2250. \.{for}&|alpha:|$|force|\,\stars$\cr
  2251. \.{function}&|proc:|$|force|\,|backup|\,\stars\,|cancel|$\qquad
  2252.   |intro:|$|indent|\,\.{\\\ }$\cr
  2253. \.{goto}&|intro:|\stars\cr
  2254. \.{if}&|cond:|\qquad|alpha:|$|force|\,\stars$\cr
  2255. \.{in}&|math:|\.{\\in}\cr
  2256. \.{label}&|intro:|$|force|\,|backup|\,\stars$\cr
  2257. \.{mod}&|math:|$|math_bin|\,\stars\,\.\}$\cr
  2258. \.{nil}&|simp:|\stars\cr
  2259. \.{not}&|math:|\.{\\R}\cr
  2260. \.{of}&|omega:|\stars\cr
  2261. \.{or}&|math:|\.{\\V}\cr
  2262. \.{packed}&|intro:|\stars\cr
  2263. \.{procedure}&|proc:|$|force|\,|backup|\,\stars\,|cancel|$\qquad
  2264.   |intro:|$|indent|\,\.{\\\ }$\cr
  2265. \.{program}&|proc:|$|force|\,|backup|\,\stars\,|cancel|$\qquad
  2266.   |intro:|$|indent|\,\.{\\\ }$\cr
  2267. \.{record}&|record_head:|\stars\qquad|intro:|\cr
  2268. \.{repeat}&|beginning:|$|force|\,|indent|\,\stars\,|cancel|$\qquad|intro:|\cr
  2269. \.{set}&|alpha:|\stars\cr
  2270. \.{then}&|omega:|\stars\cr
  2271. \.{to}&|math:|$|math_rel|\,\stars\,\.\}$\cr
  2272. \.{type}&|intro:|$|force|\,|backup|\,\stars$\cr
  2273. \.{until}&|terminator:|\qquad|close:|$|force|\,|backup|\,\stars$\qquad
  2274.   |clause:|\cr
  2275. \.{var}&|var_head:|$|force|\,|backup|\,\stars\,|cancel|$\qquad|intro:|\cr
  2276. \.{while}&|alpha:|$|force|\,\stars$\cr
  2277. \.{with}&|alpha:|$|force|\,\stars$\cr
  2278. \.{xclause}&|alpha:|$|force|\,\.{\\\~}$\qquad|omega:|\stars\cr
  2279. \.{@@\'}$\,$const&|simp:|\.{\\O\{}\hbox{const}\.\}\cr
  2280. \.{@@"}$\,$const&|simp:|\.{\\H\{}\hbox{const}\.\}\cr
  2281. \.{@@\$}&|simp:|\.{\\)}\cr
  2282. \.{@@\\}&|simp:|\.{\\]}\cr
  2283. \.{@@,}&|math:|\.{\\,}\cr
  2284. \.{@@t}$\,$stuff$\,$\.{@@>}&|simp:|\.{\\hbox\{{\rm$\,$stuff$\,$}\}}\cr
  2285. \.{@@<}$\,$module$\,$\.{@@>}&|mod_scrap:|\.{\\X$n$:{\rm$\,$module$\,$}\\X}\cr
  2286. \.{@@\#}&|comment:||big_force|\cr
  2287. \.{@@/}&|comment:||force|\cr
  2288. \.{@@\char'174}&|simp:|$|opt|\,\.0$\cr
  2289. \.{@@+}&|comment:|$|big_cancel|\,\.{\\\ }\,|big_cancel|$\cr
  2290. \.{@@;}&|semi:|\cr
  2291. \.{@@\&}&|math:|\.{\\J}\cr
  2292. \.{@@\{}&|math:|\.{\\B}\cr
  2293. \.{@@\}}&|math:|\.{\\T}\cr}
  2294. \yskip\noindent When a string is output, certain characters are preceded by
  2295. `\.\\' signs so that they will print properly.
  2296. A comment in the input will be combined with the preceding
  2297. |omega| or |semi| scrap, or with the following |terminator| scrap, if
  2298. possible; otherwise it will be inserted as a separate |terminator| scrap.
  2299. An additional ``comment'' is effectively appended at the end of the
  2300. \PASCAL\ text, just before translation begins; this consists of a |cancel|
  2301. token in the case of \PASCAL\ text in \pb, otherwise it consists of a
  2302. |force| token.
  2303. From this table it is evident that \.{WEAVE} will parse a lot of non-\PASCAL\
  2304. programs. For example, the reserved words `\.{for}' and `\.{array}' are
  2305. treated in an identical way by \.{WEAVE} from a syntactic standpoint,
  2306. and semantically they are equivalent except that a forced line break occurs
  2307. just before `\&{for}'; \PASCAL\ programmers may well be surprised at this
  2308. similarity. The idea is to keep \.{WEAVE}'s rules as simple as possible,
  2309. consistent with doing a reasonable job on syntactically correct \PASCAL\
  2310. programs. The production rules below have been formulated in the same
  2311. spirit of ``almost anything goes.''
  2312. @ Here is a table of all the productions. The reader can best get a feel for
  2313. @^productions, table of@>
  2314. how they work by trying them out by hand on small examples; no amount of
  2315. explanation will be as effective as watching the rules in action.
  2316. Parsing can also be watched by debugging with `\.{@@2}'.
  2317. \def\[#1]{\quad$\dleft#1\dright$}
  2318. \def\sp{\.{\ }}
  2319. \yskip
  2320. \halign to\the\hsize{\hfil\it# &
  2321.   #\hfil\hskip-200pt\tabskip 0pt plus 100pt&
  2322.   #\hfil\tabskip0pt\cr
  2323. &Production categories\[\hbox{translations}]&Remarks\cr
  2324. \noalign{\yskip}
  2325. 1&|alpha@,math@,colon| $\RA$ |alpha@,math|&e.g., |case v:boolean of|\cr
  2326. 2&|alpha@,math@,omega| $\RA$ |clause|\[C=A\,\sp\,\.\$\,M\,\.\$\,\sp\,|indent|\,
  2327. O]&e.g., |while x>0 do|\cr
  2328. 3&|alpha@,omega| $\RA$ |clause|\[C=A\,\sp\,|indent|\,O]&e.g., |file of|\cr
  2329. 4&|alpha@,simp| $\RA$ |alpha@,math|&convert to math mode\cr
  2330. 5&|beginning@,close@,(terminator@t or @>stmt)| $\RA$ |stmt|&compound statement
  2331. ends\cr
  2332. 6&|beginning@,stmt| $\RA$ |beginning|\[B_2=B_1\,|break_space|\,S]&compound
  2333. statement grows\cr
  2334. 7&|case_head@,casey@,clause| $\RA$ |case_head|\[C_4=C_1\,|outdent|\,C_2\,C_3]&
  2335. variant records\cr
  2336. 8&|case_head@,close@,terminator| $\RA$ |stmt|\[S=C_1\,|cancel|\,|outdent|\,
  2337. C_2\,T]&end of case statement\cr
  2338. 9&|case_head@,stmt| $\RA$ |case_head|\[C_2=C_1\,|force|\,S]&case statement
  2339. grows\cr
  2340. 10&|casey@,clause| $\RA$ |case_head|&beginning of case statement\cr
  2341. 11&|clause@,stmt| $\RA$ |stmt|\[S_2=C\,|break_space|\,S_1\,|cancel|\,|outdent|\,
  2342. |force|]&end of controlled statement\cr
  2343. 12&|cond@,clause@,stmt@,elsie| $\RA$ |clause|\[C_3=C_1\,C_2\,|break_space|\,S\,
  2344. E\,\sp\,|cancel|]&complete conditional\cr
  2345. 13&|cond@,clause@,stmt| $\RA$ |stmt|\cr
  2346. &\qquad\[S_2=C_1\,C_2\,|break_space|\,S_1\,
  2347. |cancel|\,|outdent|\,|force|]&incomplete conditional\cr
  2348. 14&|elsie| $\RA$ |intro|&unmatched else\cr
  2349. 15&|exp@,math@,simp|* $\RA$ |math|\[M_2=E\,M_1\,S\,\.\}]&signed exponent\cr
  2350. 16&|exp@,simp|* $\RA$ |math|\[M=E\,S\,\.\}]&unsigned exponent\cr
  2351. 17&|intro@,stmt| $\RA$ |stmt|\[S_2=I\,\sp\,|opt|\,\.7\,|cancel|\,S_1]&labeled
  2352. statement, etc.\cr
  2353. 18&|math@,close| $\RA$ |stmt@,close|\[S=\.\$\,M\,\.\$]&end of field list\cr
  2354. 19&|math@,colon| $\RA$ |intro|\[I=|force|\,|backup|\,\.\$\,M\,\.\$\,C]&compound
  2355. label\cr
  2356. 20&|math@,math| $\RA$ |math|&simple concatenation\cr
  2357. 21&|math@,simp| $\RA$ |math|&simple concatenation\cr
  2358. 22&|math@,stmt| $\RA$ |stmt|\cr
  2359. &\qquad\[S_2=\.\$\,M\,\.\$\,|indent|\,|break_space|\,
  2360. S_1\,|cancel|\,|outdent|\,|force|]¯o or type definition\cr
  2361. 23&|math@,terminator| $\RA$ |stmt|\[S=\.\$\,M\,\.\$\,T]&statement involving
  2362. math\cr
  2363. 24&|mod_scrap@,(terminator@t or @>semi)| $\RA$ |stmt|\[S=M\,T\,|force|]&module
  2364. like a statement\cr
  2365. 25&|mod_scrap| $\RA$ |simp|&module unlike a statement\cr
  2366. 26&|open@,case_head@,close| $\RA$ |math|\[M=O\,\.\$\,|cancel|\,C_1\,
  2367. |cancel|\,|outdent|\,\.\$\,C_2]&case in field list\cr
  2368. 27&|open@,close| $\RA$ |math|\[M=O\,\.\\\,\.,\,C]&empty set |[]|\cr
  2369. 28&|open@,math@,case_head@,close| $\RA$ |math|\cr
  2370. &\qquad\[M_2=O\,M_1\,\.\$\,|cancel|\,
  2371. C_1\,|cancel|\,|outdent|\,\.\$\,C_2]&case in field list\cr
  2372. 29&|open@,math@,close| $\RA$ |math|&parenthesized group\cr
  2373. 30&|open@,math@,colon| $\RA$ |open@,math|&colon in parentheses\cr
  2374. 31&|open@,math@,proc@,intro| $\RA$ |open@,math|\[M_2=M_1\,|math_op|\,|cancel|\,
  2375. P\,\.\}]&|procedure| in parentheses\cr
  2376. 32&|open@,math@,semi| $\RA$ |open@,math|\[M_2=M_1\,S\,\.\\\,\.,\,|opt|\,
  2377. \.5]&semicolon in parentheses\cr
  2378. 33&|open@,math@,var_head@,intro| $\RA$ |open@,math|\[M_2=M_1\,|math_op|\,
  2379. |cancel|\,V\,\.\}]&|var| in parentheses\cr
  2380. 34&|open@,proc@,intro| $\RA$ |open@,math|\[M=|math_op|\,|cancel|\,
  2381. P\,\.\}]&|procedure| in parentheses\cr
  2382. 35&|open@,simp| $\RA$ |open@,math|&convert to math mode\cr
  2383. 36&|open@,stmt@,close| $\RA$ |math|\[M=O\,\.\$\,|cancel|\,S\,|cancel|\,
  2384. \.\$\,C]&field list\cr
  2385. 37&|open@,var_head@,intro| $\RA$ |open@,math|\[M=|math_op|\,|cancel|\,V\,
  2386. \.\}]&|var| in parentheses\cr
  2387. 38&|proc@,beginning@,close@,terminator| $\RA$ |stmt|\[S=P\,|cancel|\,
  2388. |outdent|\,B\,C\,T]&end of procedure declaration\cr
  2389. 39&|proc@,stmt| $\RA$ |proc|\[P_2=P_1\,|break_space|\,S]&procedure declaration
  2390. grows\cr
  2391. 40&|record_head@,intro@,casey| $\RA$ |casey|\[C_2=R\,I\,\sp\,|cancel|\,C_1]&
  2392. \&{record case} $\ldots$\cr
  2393. 41&|record_head| $\RA$ |case_head|\[C=|indent|\,R\,|cancel|]&other \&{record}
  2394. structures\cr
  2395. 42&|semi| $\RA$ |terminator|&semicolon after statement\cr
  2396. 43&|simp@,close| $\RA$ |stmt@,close|&end of field list\cr
  2397. 44&|simp@,colon| $\RA$ |intro|\[I=|force|\,|backup|\,S\,C]&simple label\cr
  2398. 45&|simp@,math| $\RA$ |math|&simple concatenation\cr
  2399. 46&|simp@,mod_scrap| $\RA$ |mod_scrap|&in emergencies\cr
  2400. 47&|simp@,simp| $\RA$ |simp|&simple concatenation\cr
  2401. 48&|simp@,terminator| $\RA$ |stmt|&simple statement\cr
  2402. 49&|stmt@,stmt| $\RA$ |stmt|\[S_3=S_1\,|break_space|\,S_2]&adjacent
  2403. statements\cr
  2404. 50&|terminator| $\RA$ |stmt|&empty statement\cr
  2405. 51&|var_head@,beginning| $\RA$ |stmt@,beginning|&end of variable
  2406. declarations\cr
  2407. 52&|var_head@,math@,colon| $\RA$ |var_head@,intro|\[I=\.\$\,M\,\.\$\,C]&
  2408. variable declaration\cr
  2409. 53&|var_head@,simp@,colon| $\RA$ |var_head@,intro|&variable declaration\cr
  2410. 54&|var_head@,stmt| $\RA$ |var_head|\[V_2=V_1\,|break_space|\,S]&variable
  2411. declarations grow\cr}
  2412. \yskip\noindent
  2413. Translations are not specified here when they are simple concatenations
  2414. of the scraps that change. For example, the full translation of
  2415. `|open@,math@,colon| $\RA$ |open@,math|' is $O_2=O_1$, $M_2=M_1C$.
  2416. The notation `|simp|*', in the |exp|-related productions above,
  2417. stands for a |simp| scrap that isn't followed by another |simp|.
  2418. @* Implementing the productions.
  2419. When \PASCAL\ text is to be processed with the grammar above, we put its
  2420. initial scraps $s_1\ldots s_n$ into two arrays |cat[1..n]| and |trans[1..n]|.
  2421. The value of |cat[k]| is simply a category code from the list above; the
  2422. value of |trans[k]| is a text pointer, i.e., an index into |tok_start|.
  2423. Our production rules have the nice property that the right-hand side is never
  2424. longer than the left-hand side. Therefore it is convenient to use sequential
  2425. allocation for the current sequence of scraps. Five pointers are used to
  2426. manage the parsing:
  2427. \yskip\hang |pp| (the parsing pointer) is such that we are trying to match
  2428. the category codes |cat[pp]@,cat[pp+1]|$\,\ldots\,$ to the left-hand sides
  2429. of productions.
  2430. \yskip\hang |scrap_base|, |lo_ptr|, |hi_ptr|, and |scrap_ptr| are such that
  2431. the current sequence of scraps appears in positions |scrap_base| through
  2432. |lo_ptr| and |hi_ptr| through |scrap_ptr|, inclusive, in the |cat| and
  2433. |trans| arrays. Scraps located between |scrap_base| and |lo_ptr| have
  2434. been examined, while those in positions |>=hi_ptr| have not yet been
  2435. looked at by the parsing process.
  2436. \yskip\noindent Initially |scrap_ptr| is set to the position of the final
  2437. scrap to be parsed, and it doesn't change its value. The parsing process
  2438. makes sure that |lo_ptr>=pp+3|, since productions have as many as four terms,
  2439. by moving scraps from |hi_ptr| to |lo_ptr|. If there are
  2440. fewer than |pp+3| scraps left, the positions up to |pp+3| are filled with
  2441. blanks that will not match in any productions. Parsing stops when
  2442. |pp=lo_ptr+1| and |hi_ptr=scrap_ptr+1|.
  2443. The |trans| array elements are declared to be of type |0..10239| instead
  2444. of type |text_pointer|, because the final sorting phase of \.{WEAVE}
  2445. uses this array to contain elements of type |name_pointer|. Both
  2446. of these types are subranges of |0..10239|.
  2447. @<Glo...@>=
  2448. @!cat:array[0..max_scraps] of eight_bits; {category codes of scraps}
  2449. @!trans:array[0..max_scraps] of 0..10239; {translation texts of scraps}
  2450. @!pp:0..max_scraps; {current position for reducing productions}
  2451. @!scrap_base:0..max_scraps; {beginning of the current scrap sequence}
  2452. @!scrap_ptr:0..max_scraps; {ending of the current scrap sequence}
  2453. @!lo_ptr:0..max_scraps; {last scrap that has been examined}
  2454. @!hi_ptr:0..max_scraps; {first scrap that has not been examined}
  2455. stat@!max_scr_ptr:0..max_scraps; {largest value assumed by |scrap_ptr|}
  2456. @ @<Set init...@>=
  2457. scrap_base:=1; scrap_ptr:=0;
  2458. stat max_scr_ptr:=0; @+tats
  2459. @ Token lists in |@!tok_mem| are composed of the following kinds of
  2460. items for \TeX\ output.
  2461. \yskip\item{$\bullet$}ASCII codes and special codes like |force| and
  2462. |math_rel| represent themselves;
  2463. \item{$\bullet$}|id_flag+p| represents \.{\\\\\{{\rm identifier $p$}\}};
  2464. \item{$\bullet$}|res_flag+p| represents \.{\\\&\{{\rm identifier $p$}\}};
  2465. \item{$\bullet$}|mod_flag+p| represents module name |p|;
  2466. \item{$\bullet$}|tok_flag+p| represents token list number |p|;
  2467. \item{$\bullet$}|inner_tok_flag+p| represents token list number |p|, to be
  2468. translated without line-break controls.
  2469. @d id_flag=10240 {signifies an identifier}
  2470. @d res_flag=id_flag+id_flag {signifies a reserved word}
  2471. @d mod_flag=res_flag+id_flag {signifies a module name}
  2472. @d tok_flag==mod_flag+id_flag {signifies a token list}
  2473. @d inner_tok_flag==tok_flag+id_flag {signifies a token list in `\pb'}
  2474. @d lbrace==xchr["{"] {this avoids possible \PASCAL\ compiler confusion}
  2475. @d rbrace==xchr["}"] {because these braces might occur within comments}
  2476. @p @!debug procedure print_text(@!p:text_pointer); {prints a token list}
  2477. var j:0..max_toks; {index into |tok_mem|}
  2478. @!r:0..id_flag-1; {remainder of token after the flag has been stripped off}
  2479. begin if p>=text_ptr then print('BAD')
  2480. else for j:=tok_start[p] to tok_start[p+1]-1 do
  2481.   begin r:=tok_mem[j] mod id_flag;
  2482.   case tok_mem[j] div id_flag of
  2483.   1: begin print('\\',lbrace); print_id(r); print(rbrace);
  2484.     end; {|id_flag|}
  2485.   2: begin print('\&',lbrace); print_id(r); print(rbrace);
  2486.     end; {|res_flag|}
  2487.   3: begin print('<'); print_id(r); print('>');
  2488.     end; {|mod_flag|}
  2489.   4: print('[[',r:1,']]'); {|tok_flag|}
  2490.   5: print('|[[',r:1,']]|'); {|inner_tok_flag|}
  2491.   othercases @<Print token |r| in symbolic form@>
  2492.   endcases;
  2493.   end;
  2494. gubed
  2495. @ @<Print token |r|...@>=
  2496. case r of
  2497. math_bin: print('\mathbin',lbrace);
  2498. math_rel: print('\mathrel',lbrace);
  2499. math_op: print('\mathop',lbrace);
  2500. big_cancel: print('[ccancel]');
  2501. cancel: print('[cancel]');
  2502. indent: print('[indent]');
  2503. outdent: print('[outdent]');
  2504. backup: print('[backup]');
  2505. opt: print('[opt]');
  2506. break_space: print('[break]');
  2507. force: print('[force]');
  2508. big_force: print('[fforce]');
  2509. end_translation: print('[quit]');
  2510. othercases print(xchr[r])
  2511. endcases
  2512. @ The production rules listed above are embedded directly into the \.{WEAVE}
  2513. program, since it is easier to do this than to write an interpretive system
  2514. that would handle production systems in general. Several macros are defined
  2515. here so that the program for each production is fairly short.
  2516. All of our productions conform to the general notion that some |k|
  2517. consecutive scraps starting at some position |j| are to be replaced by a
  2518. single scrap of some category |c| whose translations is composed from the
  2519. translations of the disappearing scraps. After this production has been
  2520. applied, the production pointer |pp| should change by an amount |d|. Such
  2521. a production can be represented by the quadruple $(j,k,c,d)$. For example,
  2522. the production `|simp@,math| $\RA$ |math|' would be represented by
  2523. `$(|pp|,2,|math|,-1)$'; in this case the pointer $pp$ should decrease by 1
  2524. after the production has been applied, because some productions with
  2525. |math| in their second positions might now match, but no productions have
  2526. |math| in the third or fourth position of their left-hand sides. Note that
  2527. the value of |d| is determined by the whole collection of productions, not
  2528. by an individual one. Consider the further example
  2529. `|var_head@,math@,colon| $\RA$ |var_head@,intro|', which is represented by
  2530. `$(|pp|+1,2,|intro|,+1)$'; the $+1$ here is deduced by looking at the
  2531. grammar and seeing that no matches could possibly occur at positions |<=pp|
  2532. after this production has been applied. The determination of |d| has been
  2533. done by hand in each case, based on the full set of productions but not on
  2534. the grammar of \PASCAL\ or on the rules for constructing the initial
  2535. scraps.
  2536. We also attach a serial number of each production, so that additional
  2537. information is available when debugging. For example, the program below
  2538. contains the statement `|reduce(pp+1,2,intro,+1)(52)|' when it implements
  2539. the production just mentioned.
  2540. Before calling |reduce|, the program should have appended the tokens of
  2541. the new translation to the |tok_mem| array. We commonly want to append
  2542. copies of several existing translations, and macros are defined to
  2543. simplify these common cases. For example, |app2(pp)| will append the
  2544. translations of two consecutive scraps, |trans[pp]| and |trans[pp+1]|, to
  2545. the current token list. If the entire new translation is formed in this
  2546. way, we write `$|squash|(j,k,c,d)$' instead of `$|reduce|(j,k,c,d)$'. For
  2547. example, `|squash(pp,2,math,-1)|' is an abbreviation for `|app2(pp);
  2548. reduce(pp,2,math,-1)|'.
  2549. The code below is an exact translation of the production rules into
  2550. \PASCAL, using such macros, and the reader should have no difficulty
  2551. understanding the format by comparing the code with the symbolic
  2552. productions as they were listed earlier.
  2553. {\sl Caution:\/} The macros |app|, |app1|, |app2|, and |app3| are
  2554. sequences of statements that are not enclosed with |begin| and $|end|$,
  2555. because such delimiters would make the \PASCAL\ program much longer. This
  2556. means that it is necessary to write |begin| and |end| explicitly when such
  2557. a macro is used as a single statement. Several mysterious bugs in the
  2558. original programming of \.{WEAVE} were caused by a failure to remember
  2559. this fact.  Next time the author will know better.
  2560. @d production(#)==@!debug prod(#) gubed; goto found
  2561. @d reduce(#)==red(#); production
  2562. @d production_end(#)==@!debug prod(#) gubed; goto found;
  2563.   end
  2564. @d squash(#)==begin sq(#); production_end
  2565. @d app(#)==tok_mem[tok_ptr]:=#; incr(tok_ptr) {this is like |app_tok|,
  2566.   but it doesn't test for overflow}
  2567. @d app1(#)==tok_mem[tok_ptr]:=tok_flag+trans[#]; incr(tok_ptr)
  2568. @d app2(#)==app1(#);app1(#+1)
  2569. @d app3(#)==app2(#);app1(#+2)
  2570. @ Let us consider the big case statement for productions now, before looking
  2571. at its context. We want to design the program so that this case statement
  2572. works, so we might as well not keep ourselves in suspense about exactly what
  2573. code needs to be provided with a proper environment.
  2574. The code here is more complicated than it need be, since some popular
  2575. \PASCAL\ compilers are unable to deal with procedures that contain a lot
  2576. of program text. The |translate| procedure, which incorporates the |case|
  2577. statement here, would become too long for those compilers if we did
  2578. not do something to split the cases into parts. Therefore
  2579. a separate procedure called |five_cases| has been introduced.
  2580. @^split procedures@>
  2581. This auxiliary procedure contains approximately half of the program text
  2582. that |translate| would otherwise have had. There's also a procedure
  2583. called |alpha_cases|, which turned out to be necessary because the best
  2584. two-way split wasn't good enough. The procedure could be split further
  2585. in an analogous manner, but the present scheme works on all compilers
  2586. known to the author.
  2587. @<Match a production at |pp|, or increase |pp| if there is no match@>=
  2588. if cat[pp]<=alpha then
  2589.   if cat[pp]<alpha then five_cases@+else alpha_cases
  2590. else  begin case cat[pp] of
  2591.   case_head: @<Cases for |case_head|@>;
  2592.   casey: @<Cases for |casey|@>;
  2593.   clause: @<Cases for |clause|@>;
  2594.   cond: @<Cases for |cond|@>;
  2595.   elsie: @<Cases for |elsie|@>;
  2596.   exp: @<Cases for |exp|@>;
  2597.   mod_scrap: @<Cases for |mod_scrap|@>;
  2598.   proc: @<Cases for |proc|@>;
  2599.   record_head: @<Cases for |record_head|@>;
  2600.   semi: @<Cases for |semi|@>;
  2601.   stmt: @<Cases for |stmt|@>;
  2602.   terminator: @<Cases for |terminator|@>;
  2603.   var_head: @<Cases for |var_head|@>;
  2604.   othercases do_nothing
  2605.   endcases;@/
  2606.   incr(pp); {if no match was found, we move to the right}
  2607.   found: end
  2608. @ Here are the procedures that need to be present for the reason just
  2609. explained.
  2610. @<Declaration of subprocedures for |translate|@>=
  2611. procedure five_cases; {handles almost half of the syntax}
  2612. label found;
  2613. begin case cat[pp] of
  2614. beginning: @<Cases for |beginning|@>;
  2615. intro: @<Cases for |intro|@>;
  2616. math: @<Cases for |math|@>;
  2617. open: @<Cases for |open|@>;
  2618. simp: @<Cases for |simp|@>;
  2619. othercases do_nothing
  2620. endcases;@/
  2621. incr(pp); {if no match was found, we move to the right}
  2622. found: end;
  2623. procedure alpha_cases;
  2624. label found;
  2625. begin @<Cases for |alpha|@>;
  2626. incr(pp); {if no match was found, we move to the right}
  2627. found: end;
  2628. @ Now comes the code that tries to match each production that starts
  2629. with a particular type of scrap. Whenever a match is discovered,
  2630. the |squash| or |reduce| macro will cause the appropriate action
  2631. to be performed, followed by |goto found|.
  2632. @<Cases for |alpha|@>=
  2633. if cat[pp+1]=math then
  2634.   begin if cat[pp+2]=colon then squash(pp+1,2,math,0)(1)
  2635.   else if cat[pp+2]=omega then
  2636.     begin app1(pp); app(" "); app("$"); app1(pp+1);
  2637.     app("$"); app(" "); app(indent); app1(pp+2);
  2638.     reduce(pp,3,clause,-2)(2);
  2639.     end;
  2640.   end
  2641. else if cat[pp+1]=omega then
  2642.   begin app1(pp); app(" "); app(indent); app1(pp+1);
  2643.   reduce(pp,2,clause,-2)(3);
  2644.   end
  2645. else if cat[pp+1]=simp then squash(pp+1,1,math,0)(4)
  2646. @ @<Cases for |beginning|@>=
  2647. if cat[pp+1]=close then
  2648.   begin if (cat[pp+2]=terminator)or(cat[pp+2]=stmt) then
  2649.     squash(pp,3,stmt,-2)(5);
  2650.   end
  2651. else if cat[pp+1]=stmt then
  2652.   begin app1(pp); app(break_space); app1(pp+1);
  2653.   reduce(pp,2,beginning,-1)(6);
  2654.   end
  2655. @ @<Cases for |case_head|@>=
  2656. if cat[pp+1]=casey then
  2657.   begin if cat[pp+2]=clause then
  2658.     begin app1(pp); app(outdent); app2(pp+1);
  2659.     reduce(pp,3,case_head,0)(7);
  2660.     end;
  2661.   end
  2662. else if cat[pp+1]=close then
  2663.   begin if cat[pp+2]=terminator then
  2664.     begin app1(pp); app(cancel); app(outdent); app2(pp+1);
  2665.     reduce(pp,3,stmt,-2)(8);
  2666.     end;
  2667.   end
  2668. else if cat[pp+1]=stmt then
  2669.   begin app1(pp); app(force); app1(pp+1);
  2670.   reduce(pp,2,case_head,0)(9);
  2671.   end
  2672. @ @<Cases for |casey|@>=
  2673. if cat[pp+1]=clause then squash(pp,2,case_head,0)(10)
  2674. @ @<Cases for |clause|@>=
  2675. if cat[pp+1]=stmt then
  2676.   begin app1(pp); app(break_space); app1(pp+1);
  2677.   app(cancel); app(outdent);
  2678.   app(force); reduce(pp,2,stmt,-2)(11);
  2679.   end
  2680. @ @<Cases for |cond|@>=
  2681. if (cat[pp+1]=clause)and(cat[pp+2]=stmt) then
  2682.   if cat[pp+3]=elsie then
  2683.     begin app2(pp); app(break_space); app2(pp+2); app(" ");
  2684.     app(cancel); reduce(pp,4,clause,-2)(12);
  2685.     end
  2686.   else  begin app2(pp); app(break_space); app1(pp+2); app(cancel);
  2687.     app(outdent); app(force); reduce(pp,3,stmt,-2)(13);
  2688.     end
  2689. @ @<Cases for |elsie|@>=
  2690. squash(pp,1,intro,-3)(14)
  2691. @ @<Cases for |exp|@>=
  2692. if cat[pp+1]=math then
  2693.   begin if cat[pp+2]=simp then if cat[pp+3]<>simp then
  2694.     begin app3(pp); app("}"); reduce(pp,3,math,-1)(15);
  2695.     end;
  2696.   end
  2697. else if cat[pp+1]=simp then if cat[pp+2]<>simp then
  2698.   begin app2(pp); app("}"); reduce(pp,2,math,-1)(16);
  2699.   end
  2700. @ @<Cases for |intro|@>=
  2701. if cat[pp+1]=stmt then
  2702.   begin app1(pp); app(" "); app(opt); app("7");
  2703.   app(cancel); app1(pp+1); reduce(pp,2,stmt,-2)(17);
  2704.   end
  2705. @ @<Cases for |math|@>=
  2706. if cat[pp+1]=close then
  2707.   begin app("$"); app1(pp); app("$"); reduce(pp,1,stmt,-2)(18);
  2708.   end
  2709. else if cat[pp+1]=colon then
  2710.   begin app(force); app(backup); app("$"); app1(pp);
  2711.   app("$"); app1(pp+1); reduce(pp,2,intro,-3)(19);
  2712.   end
  2713. else if cat[pp+1]=math then squash(pp,2,math,-1)(20)
  2714. else if cat[pp+1]=simp then squash(pp,2,math,-1)(21)
  2715. else if cat[pp+1]=stmt then
  2716.   begin app("$"); app1(pp); app("$"); app(indent);
  2717.   app(break_space); app1(pp+1); app(cancel); app(outdent);
  2718.   app(force); reduce(pp,2,stmt,-2)(22);
  2719.   end
  2720. else if cat[pp+1]=terminator then
  2721.   begin app("$"); app1(pp); app("$"); app1(pp+1);
  2722.   reduce(pp,2,stmt,-2)(23);
  2723.   end
  2724. @ @<Cases for |mod_scrap|@>=
  2725. if (cat[pp+1]=terminator)or(cat[pp+1]=semi) then
  2726.   begin app2(pp); app(force); reduce(pp,2,stmt,-2)(24);
  2727.   end
  2728. else squash(pp,1,simp,-2)(25)
  2729. @ @<Cases for |open|@>=
  2730. if (cat[pp+1]=case_head)and(cat[pp+2]=close) then
  2731.   begin app1(pp); app("$"); app(cancel); app1(pp+1); app(cancel);
  2732.   app(outdent); app("$"); app1(pp+2); reduce(pp,3,math,-1)(26);
  2733.   end
  2734. else if cat[pp+1]=close then
  2735.   begin app1(pp); app("\"); app(","); app1(pp+1);
  2736. @.\\,@>
  2737.   reduce(pp,2,math,-1)(27);
  2738.   end
  2739. else if cat[pp+1]=math then @<Cases for |open@,math|@>
  2740. else if cat[pp+1]=proc then
  2741.   begin if cat[pp+2]=intro then
  2742.     begin app(math_op); app(cancel); app1(pp+1); app("}");
  2743.     reduce(pp+1,2,math,0)(34);
  2744.     end;
  2745.   end
  2746. else if cat[pp+1]=simp then squash(pp+1,1,math,0)(35)
  2747. else if (cat[pp+1]=stmt)and(cat[pp+2]=close) then
  2748.   begin app1(pp); app("$"); app(cancel); app1(pp+1); app(cancel);
  2749.   app("$"); app1(pp+2); reduce(pp,3,math,-1)(36);
  2750.   end
  2751. else if cat[pp+1]=var_head then
  2752.   begin if cat[pp+2]=intro then
  2753.     begin app(math_op); app(cancel); app1(pp+1); app("}");
  2754.     reduce(pp+1,2,math,0)(37);
  2755.     end;
  2756.   end
  2757. @ @<Cases for |open@,math|@>=
  2758. begin if (cat[pp+2]=case_head)and(cat[pp+3]=close) then
  2759.   begin app2(pp); app("$"); app(cancel); app1(pp+2); app(cancel);
  2760.   app(outdent); app("$"); app1(pp+3); reduce(pp,4,math,-1)(28);
  2761.   end
  2762. else if cat[pp+2]=close then squash(pp,3,math,-1)(29)
  2763. else if cat[pp+2]=colon then squash(pp+1,2,math,0)(30)
  2764. else if cat[pp+2]=proc then
  2765.   begin if cat[pp+3]=intro then
  2766.     begin app1(pp+1); app(math_op); app(cancel);
  2767.     app1(pp+2); app("}"); reduce(pp+1,3,math,0)(31);
  2768.     end;
  2769.   end
  2770. else if cat[pp+2]=semi then
  2771.   begin app2(pp+1); app("\"); app(","); app(opt); app("5");
  2772. @.\\,@>
  2773.   reduce(pp+1,2,math,0)(32);
  2774.   end
  2775. else if cat[pp+2]=var_head then
  2776.   begin if cat[pp+3]=intro then
  2777.     begin app1(pp+1); app(math_op); app(cancel);
  2778.     app1(pp+2); app("}"); reduce(pp+1,3,math,0)(31);
  2779.     end;
  2780.   end;
  2781. @ @<Cases for |proc|@>=
  2782. if cat[pp+1]=beginning then
  2783.   begin if (cat[pp+2]=close)and(cat[pp+3]=terminator) then
  2784.     begin app1(pp); app(cancel); app(outdent); app3(pp+1);
  2785.     reduce(pp,4,stmt,-2)(38);
  2786.     end;
  2787.   end
  2788. else if cat[pp+1]=stmt then
  2789.   begin app1(pp); app(break_space); app1(pp+1);
  2790.   reduce(pp,2,proc,-2)(39);
  2791.   end
  2792. @ @<Cases for |record_head|@>=
  2793. if (cat[pp+1]=intro)and(cat[pp+2]=casey) then
  2794.   begin app2(pp); app(" "); app(cancel); app1(pp+2);
  2795.   reduce(pp,3,casey,-2)(40);
  2796.   end
  2797. else  begin app(indent); app1(pp); app(cancel);
  2798.   reduce(pp,1,case_head,0)(41);
  2799.   end
  2800. @ @<Cases for |semi|@>=
  2801. squash(pp,1,terminator,-3)(42)
  2802. @ @<Cases for |simp|@>=
  2803. if cat[pp+1]=close then squash(pp,1,stmt,-2)(43)
  2804. else if cat[pp+1]=colon then
  2805.   begin app(force); app(backup); app2(pp); reduce(pp,2,intro,-3)(44);
  2806.   end
  2807. else if cat[pp+1]=math then squash(pp,2,math,-1)(45)
  2808. else if cat[pp+1]=mod_scrap then squash(pp,2,mod_scrap,0)(46)
  2809. else if cat[pp+1]=simp then squash(pp,2,simp,-2)(47)
  2810. else if cat[pp+1]=terminator then squash(pp,2,stmt,-2)(48)
  2811. @ @<Cases for |stmt|@>=
  2812. if cat[pp+1]=stmt then
  2813.   begin app1(pp); app(break_space); app1(pp+1);
  2814.   reduce(pp,2,stmt,-2)(49);
  2815.   end
  2816. @ @<Cases for |terminator|@>=
  2817. squash(pp,1,stmt,-2)(50)
  2818. @ @<Cases for |var_head|@>=
  2819. if cat[pp+1]=beginning then squash(pp,1,stmt,-2)(51)
  2820. else if cat[pp+1]=math then
  2821.   begin if cat[pp+2]=colon then
  2822.     begin app("$"); app1(pp+1); app("$"); app1(pp+2);
  2823.     reduce(pp+1,2,intro,+1)(52);
  2824.     end;
  2825.   end
  2826. else if cat[pp+1]=simp then
  2827.   begin if cat[pp+2]=colon then squash(pp+1,2,intro,+1)(53);
  2828.   end
  2829. else if cat[pp+1]=stmt then
  2830.   begin app1(pp); app(break_space); app1(pp+1);
  2831.   reduce(pp,2,var_head,-2)(54);
  2832.   end
  2833. @ The `|freeze_text|' macro is used to give official status to a token list.
  2834. Before saying |freeze_text|, items are appended to the current token list,
  2835. and we know that the eventual number of this token list will be the current
  2836. value of |text_ptr|. But no list of that number really exists as yet,
  2837. because no ending point for the current list has been
  2838. stored in the |tok_start| array. After saying |freeze_text|, the
  2839. old current token list becomes legitimate, and its number is the current
  2840. value of |text_ptr-1| since |text_ptr| has been increased. The new
  2841. current token list is empty and ready to be appended to.
  2842. Note that |freeze_text| does not check to see that |text_ptr| hasn't gotten
  2843. too large, since it is assumed that this test was done beforehand.
  2844. @d freeze_text==incr(text_ptr); tok_start[text_ptr]:=tok_ptr
  2845. @ The `|reduce|' macro used in our code for productions actually calls on
  2846. a procedure named `|red|', which makes the appropriate changes to the
  2847. scrap list.
  2848. @p procedure red(@!j:sixteen_bits; @!k:eight_bits; @!c:eight_bits;
  2849.   @!d:integer);
  2850. var i:0..max_scraps; {index into scrap memory}
  2851. begin cat[j]:=c; trans[j]:=text_ptr; freeze_text;
  2852. if k>1 then
  2853.   begin for i:=j+k to lo_ptr do
  2854.     begin cat[i-k+1]:=cat[i]; trans[i-k+1]:=trans[i];
  2855.     end;
  2856.   lo_ptr:=lo_ptr-k+1;
  2857.   end;
  2858. @<Change |pp| to $\max(|scrap_base|,|pp+d|)$@>;
  2859. @ @<Change |pp| to $\max(|scrap_base|,|pp+d|)$@>=
  2860. if pp+d>=scrap_base then pp:=pp+d
  2861. else pp:=scrap_base
  2862. @ Similarly, the `|squash|' macro invokes a procedure called `|sq|'. This
  2863. procedure takes advantage of the simplification that occurs when |k=1|.
  2864. @p procedure sq(@!j:sixteen_bits; @!k:eight_bits; @!c:eight_bits;
  2865.   @!d:integer);
  2866. var i:0..max_scraps; {index into scrap memory}
  2867. begin if k=1 then
  2868.   begin cat[j]:=c; @<Change |pp|...@>;
  2869.   end
  2870. else  begin for i:=j to j+k-1 do
  2871.     begin app1(i);
  2872.     end;
  2873.   red(j,k,c,d);
  2874.   end;
  2875. @ Here now is the code that applies productions as long as possible. It
  2876. requires two local labels (|found| and |done|), as well as a local
  2877. variable (|i|).
  2878. @<Reduce the scraps using the productions until no more rules apply@>=
  2879. loop@+begin @<Make sure the entries |cat[pp..(pp+3)]| are defined@>;
  2880.   if (tok_ptr+8>max_toks)or(text_ptr+4>max_texts) then
  2881.     begin stat if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;
  2882.     if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  2883.     tats@;@/
  2884.     overflow('token/text');
  2885.     end;
  2886.   if pp>lo_ptr then goto done;
  2887.   @<Match a production...@>;
  2888.   end;
  2889. done:
  2890. @ If we get to the end of the scrap list, category codes equal to zero are
  2891. stored, since zero does not match anything in a production.
  2892. @<Make sure the entries...@>=
  2893. if lo_ptr<pp+3 then
  2894.   begin repeat if hi_ptr<=scrap_ptr then
  2895.     begin incr(lo_ptr);@/
  2896.     cat[lo_ptr]:=cat[hi_ptr]; trans[lo_ptr]:=trans[hi_ptr];@/
  2897.     incr(hi_ptr);
  2898.     end;
  2899.   until (hi_ptr>scrap_ptr)or(lo_ptr=pp+3);
  2900.   for i:=lo_ptr+1 to pp+3 do cat[i]:=0;
  2901.   end
  2902. @ If \.{WEAVE} is being run in debugging mode, the production numbers and
  2903. current stack categories will be printed out when |tracing| is set to 2;
  2904. a sequence of two or more irreducible scraps will be printed out when
  2905. |tracing| is set to 1.
  2906. @.\AT!2@>
  2907. @.\AT!1@>
  2908. @<Glo...@>=
  2909. @!debug@!tracing:0..2; {can be used to show parsing details}
  2910. gubed
  2911. @ The |prod| procedure is called in debugging mode just after |reduce| or
  2912. |squash|; its parameter is the number of the production that has just
  2913. been applied.
  2914. @p @!debug procedure prod(@!n:eight_bits); {shows current categories}
  2915. var k:1..max_scraps; {index into |cat|}
  2916. begin if tracing=2 then
  2917.   begin print_nl(n:1,':');
  2918.   for k:=scrap_base to lo_ptr do
  2919.     begin if k=pp then print('*') @+ else print(' ');
  2920.     print_cat(cat[k]);
  2921.     end;
  2922.   if hi_ptr<=scrap_ptr then print('...'); {indicate that more is coming}
  2923.   end;
  2924. gubed
  2925. @ The |translate| function assumes that scraps have been stored in
  2926. positions |scrap_base| through |scrap_ptr| of |cat| and |trans|. It
  2927. appends a |terminator| scrap and begins to apply productions as much as
  2928. possible. The result is a token list containing the translation of
  2929. the given sequence of scraps.
  2930. After calling |translate|, we will have |text_ptr+3<=max_texts| and
  2931. |tok_ptr+6<=max_toks|, so it will be possible to create up to three token
  2932. lists with up to six tokens without checking for overflow. Before calling
  2933. |translate|, we should have |text_ptr<max_texts| and |scrap_ptr<max_scraps|,
  2934. since |translate| might add a new text and a new scrap before it checks
  2935. for overflow.
  2936. @p @<Declaration of subprocedures for |translate|@>@;
  2937. function translate:text_pointer; {converts a sequence of scraps}
  2938. label done,found;
  2939. var i: 1..max_scraps; {index into |cat|}
  2940. @!j:0..max_scraps; {runs through final scraps}
  2941. @!k:0..long_buf_size; {index into |buffer|}
  2942. begin pp:=scrap_base; lo_ptr:=pp-1; hi_ptr:=pp;
  2943. @<If tracing, print an indication of where we are@>;
  2944. @<Reduce the scraps...@>;
  2945. if (lo_ptr=scrap_base)and(cat[lo_ptr]<>math) then translate:=trans[lo_ptr]
  2946. else @<Combine the irreducible scraps that remain@>;
  2947. @ If the initial sequence of scraps does not reduce to a single scrap,
  2948. we concatenate the translations of all remaining scraps, separated by
  2949. blank spaces, with dollar signs surrounding the translations of |math|
  2950. scraps.
  2951. @<Combine the irreducible...@>=
  2952. begin @<If semi-tracing, show the irreducible scraps@>;
  2953. for j:=scrap_base to lo_ptr do
  2954.   begin if j<>scrap_base then
  2955.     begin app(" ");
  2956.     end;
  2957.   if cat[j]=math then
  2958.     begin app("$");
  2959.     end;
  2960.   app1(j);
  2961.   if cat[j]=math then
  2962.     begin app("$");
  2963.     end;
  2964.   if tok_ptr+6>max_toks then overflow('token');
  2965.   end;
  2966. freeze_text; translate:=text_ptr-1;
  2967. @ @<If semi-tracing, show the irreducible scraps@>=
  2968. @!debug if (lo_ptr>scrap_base)and(tracing=1) then
  2969.   begin print_nl('Irreducible scrap sequence in section ',module_count:1);
  2970.   print_ln(':'); mark_harmless;
  2971.   for j:=scrap_base to lo_ptr do
  2972.     begin print(' '); print_cat(cat[j]);
  2973.     end;
  2974.   end;
  2975. gubed
  2976. @ @<If tracing,...@>=
  2977. @!debug if tracing=2 then
  2978.   begin print_nl('Tracing after l.',line:1,':'); mark_harmless;
  2979.   if loc>50 then
  2980.     begin print('...');
  2981.     for k:=loc-50 to loc do print(xchr[buffer[k-1]]);
  2982.     end
  2983.   else for k:=1 to loc do print(xchr[buffer[k-1]]);
  2984.   end
  2985. gubed
  2986. @* Initializing the scraps.
  2987. If we are going to use the powerful production mechanism just developed, we
  2988. must get the scraps set up in the first place, given a \PASCAL\ text. A table
  2989. of the initial scraps corresponding to \PASCAL\ tokens appeared above in the
  2990. section on parsing; our goal now is to implement that table. We shall do this
  2991. by implementing a subroutine called |Pascal_parse| that is analogous to the
  2992. |Pascal_xref| routine used during phase one.
  2993. Like |Pascal_xref|, the |Pascal_parse| procedure starts with the current
  2994. value of |next_control| and it uses the operation |next_control:=get_next|
  2995. repeatedly to read \PASCAL\ text until encountering the next `\v' or
  2996. `\.\{', or until |next_control>=format|. The scraps corresponding to what
  2997. it reads are appended into the |cat| and |trans| arrays, and |scrap_ptr|
  2998. is advanced.
  2999. Like |prod|, this procedure has to split into pieces so that each
  3000. part is short enough to be handled by \PASCAL\ compilers that discriminate
  3001. against long subroutines. This time there are two split-off routines,
  3002. called |easy_cases| and |sub_cases|.
  3003. @^split procedures@>
  3004. After studying |Pascal_parse|, we will look at the sub-procedures
  3005. |app_comment|, |app_octal|, and |app_hex| that are used in some of its
  3006. branches.
  3007. @p @<Declaration of the |app_comment| procedure@>@;
  3008. @<Declaration of the |app_octal| and |app_hex| procedures@>@;
  3009. @<Declaration of the |easy_cases| procedure@>@;
  3010. @<Declaration of the |sub_cases| procedure@>@;
  3011. procedure Pascal_parse; {creates scraps from \PASCAL\ tokens}
  3012. label reswitch, exit;
  3013. var j:0..long_buf_size; {index into |buffer|}
  3014. @!p:name_pointer; {identifier designator}
  3015. begin while next_control<format do
  3016.   begin @<Append the scrap appropriate to |next_control|@>;
  3017.   next_control:=get_next;
  3018.   if (next_control="|")or(next_control="{") then return;
  3019.   end;
  3020. exit:end;
  3021. @ The macros defined here are helpful abbreviations for the operations
  3022. needed when generating the scraps. A scrap of category |c| whose
  3023. translation has three tokens $t_1$, $t_2$, $t_3$ is generated by
  3024. |sc3|$(t_1)(t_2)(t_3)(c)$, etc.
  3025. @d s0(#)==incr(scrap_ptr); cat[scrap_ptr]:=#; trans[scrap_ptr]:=text_ptr;
  3026.   freeze_text;
  3027.   end
  3028. @d s1(#)==app(#);s0
  3029. @d s2(#)==app(#);s1
  3030. @d s3(#)==app(#);s2
  3031. @d s4(#)==app(#);s3
  3032. @d sc4==@+begin s4
  3033. @d sc3==@+begin s3
  3034. @d sc2==@+begin s2
  3035. @d sc1==@+begin s1
  3036. @d sc0(#)==begin incr(scrap_ptr); cat[scrap_ptr]:=#; trans[scrap_ptr]:=0;
  3037.   end
  3038. @d comment_scrap(#)==begin app(#); app_comment;
  3039.   end
  3040. @ @<Append the scr...@>=
  3041. @<Make sure that there is room for at least four more scraps, six more
  3042. tokens, and four more texts@>;
  3043. reswitch: case next_control of
  3044. string,verbatim: @<Append a \(string scrap@>;
  3045. identifier: @<Append an identifier scrap@>;
  3046. TeX_string: @<Append a \TeX\ string scrap@>;
  3047. othercases easy_cases
  3048. endcases
  3049. @ The |easy_cases| each result in straightforward scraps.
  3050. @<Declaration of the |easy_cases| procedure@>=
  3051. procedure easy_cases; {a subprocedure of |Pascal_parse|}
  3052. begin case next_control of
  3053. set_element_sign: sc3("\")("i")("n")(math);
  3054. @.\\in@>
  3055. double_dot: sc3("\")("t")("o")(math);
  3056. @.\\to@>
  3057. "#","$","%","^","_": sc2("\")(next_control)(math);
  3058. @.\\\#@>
  3059. @.\\\$@>
  3060. @.\\\%@>
  3061. @.\\\^@>
  3062. ignore,"|",xref_roman,xref_wildcard,xref_typewriter: do_nothing;
  3063. "(","[": sc1(next_control)(open);
  3064. ")","]": sc1(next_control)(close);
  3065. "*": sc4("\")("a")("s")("t")(math);
  3066. @.\\ast@>
  3067. ",": sc3(",")(opt)("9")(math);
  3068. ".","0","1","2","3","4","5","6","7","8","9": sc1(next_control)(simp);
  3069. ";": sc1(";")(semi);
  3070. ":": sc1(":")(colon);
  3071. @t\4@>  @<Cases involving nonstandard ASCII characters@>@;
  3072. exponent: sc3("\")("E")("{")(exp);
  3073. @.\\E@>
  3074. begin_comment: sc2("\")("B")(math);
  3075. @.\\B@>
  3076. end_comment: sc2("\")("T")(math);
  3077. @.\\T@>
  3078. octal: app_octal;
  3079. hex: app_hex;
  3080. check_sum: sc2("\")(")")(simp);
  3081. @.\\)@>
  3082. force_line: sc2("\")("]")(simp);
  3083. @.\\]@>
  3084. thin_space: sc2("\")(",")(math);
  3085. @.\\,@>
  3086. math_break: sc2(opt)("0")(simp);
  3087. line_break: comment_scrap(force);
  3088. big_line_break: comment_scrap(big_force);
  3089. no_line_break: begin app(big_cancel); app("\"); app(" ");
  3090. @.\\\ @>
  3091.   comment_scrap(big_cancel);
  3092.   end;
  3093. pseudo_semi: sc0(semi);
  3094. join: sc2("\")("J")(math);
  3095. @.\\J@>
  3096. othercases sc1(next_control)(math)
  3097. endcases;
  3098. @ @<Make sure that there is room for at least four...@>=
  3099. if (scrap_ptr+4>max_scraps)or(tok_ptr+6>max_toks)or(text_ptr+4>max_texts) then
  3100.   begin stat if scrap_ptr>max_scr_ptr then max_scr_ptr:=scrap_ptr;
  3101.   if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;
  3102.   if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  3103.   tats@;@/
  3104.   overflow('scrap/token/text');
  3105.   end
  3106. @ Some nonstandard ASCII characters may have entered \.{WEAVE} by means of
  3107. standard ones. They are converted to \TeX\ control sequences so that it is
  3108. possible to keep \.{WEAVE} from stepping beyond standard ASCII.
  3109. @<Cases involving nonstandard...@>=
  3110. not_equal: sc2("\")("I")(math);
  3111. @.\\I@>
  3112. less_or_equal: sc2("\")("L")(math);
  3113. @.\\L@>
  3114. greater_or_equal: sc2("\")("G")(math);
  3115. @.\\G@>
  3116. equivalence_sign: sc2("\")("S")(math);
  3117. @.\\S@>
  3118. and_sign: sc2("\")("W")(math);
  3119. @.\\W@>
  3120. or_sign: sc2("\")("V")(math);
  3121. @.\\V@>
  3122. not_sign: sc2("\")("R")(math);
  3123. @.\\R@>
  3124. left_arrow: sc2("\")("K")(math);
  3125. @.\\K@>
  3126. @ The following code must use |app_tok| instead of |app| in order to
  3127. protect against overflow. Note that |tok_ptr+1<=max_toks| after |app_tok|
  3128. has been used, so another |app| is legitimate before testing again.
  3129. Many of the special characters in a string must be prefixed by `\.\\' so that
  3130. \TeX\ will print them properly.
  3131. @^special string characters@>
  3132. @<Append a \(string scrap@>=
  3133. begin app("\");
  3134. if next_control=verbatim then
  3135.   begin app("=");
  3136. @.\\=@>
  3137.   end
  3138. else  begin app(".");
  3139. @.\\.@>
  3140.   end;
  3141. app("{"); j:=id_first;
  3142. while j<id_loc do
  3143.   begin case buffer[j] of
  3144.   " ","\","#","%","$","^","'","`","{","}","~","&","_":
  3145.       begin app("\");
  3146.       end;
  3147. @.\\\ @>
  3148. @.\\\\@>
  3149. @.\\\#@>
  3150. @.\\\%@>
  3151. @.\\\$@>
  3152. @.\\\^@>
  3153. @.\\\'@>
  3154. @.\\\`@>
  3155. @.\\\{@>
  3156. @.\\\}@>
  3157. @.\\\~@>
  3158. @.\\\&@>
  3159. @.\\_@>
  3160.   "@@": if buffer[j+1]="@@" then incr(j)
  3161.     else err_print('! Double @@ should be used in strings');
  3162. @.Double \AT! should be used...@>
  3163.   othercases do_nothing
  3164.   endcases;@/
  3165.   app_tok(buffer[j]); incr(j);
  3166.   end;
  3167. sc1("}")(simp);
  3168. @ @<Append a \TeX\ string scrap@>=
  3169. begin app("\"); app("h"); app("b"); app("o"); app("x");
  3170. app("{");
  3171. for j:=id_first to id_loc-1 do app_tok(buffer[j]);
  3172. sc1("}")(simp);
  3173. @ @<Append an identifier scrap@>=
  3174. begin p:=id_lookup(normal);
  3175. case ilk[p] of
  3176. normal,array_like,const_like,div_like,
  3177.   do_like,for_like,goto_like,nil_like,to_like: sub_cases(p);
  3178. @t\4@>@<Cases that generate more than one scrap@>@;
  3179. othercases begin next_control:=ilk[p]-char_like; goto reswitch;
  3180.   end {\&{and}, \&{in}, \&{not}, \&{or}}
  3181. endcases;
  3182. @ The |sub_cases| also result in straightforward scraps.
  3183. @<Declaration of the |sub_cases| procedure@>=
  3184. procedure sub_cases(@!p:name_pointer); {a subprocedure of |Pascal_parse|}
  3185. begin case ilk[p] of
  3186. normal: sc1(id_flag+p)(simp); {not a reserved word}
  3187. array_like: sc1(res_flag+p)(alpha); {\&{array}, \&{file}, \&{set}}
  3188. const_like: sc3(force)(backup)(res_flag+p)(intro);
  3189.   {\&{const}, \&{label}, \&{type}}
  3190. div_like: sc3(math_bin)(res_flag+p)("}")(math); {\&{div}, \&{mod}}
  3191. do_like: sc1(res_flag+p)(omega); {\&{do}, \&{of}, \&{then}}
  3192. for_like: sc2(force)(res_flag+p)(alpha); {\&{for}, \&{while}, \&{with}}
  3193. goto_like: sc1(res_flag+p)(intro); {\&{goto}, \&{packed}}
  3194. nil_like: sc1(res_flag+p)(simp); {\&{nil}}
  3195. to_like: sc3(math_rel)(res_flag+p)("}")(math); {\&{downto}, \&{to}}
  3196. @ @<Cases that generate more than one scrap@>=
  3197. begin_like: begin sc3(force)(res_flag+p)(cancel)(beginning); sc0(intro);
  3198.   end; {\&{begin}}
  3199. case_like: begin sc0(casey); sc2(force)(res_flag+p)(alpha);
  3200.   end; {\&{case}}
  3201. else_like: begin @<Append |terminator| if not already present@>;
  3202.   sc3(force)(backup)(res_flag+p)(elsie);
  3203.   end; {\&{else}}
  3204. end_like: begin @<Append |term...@>;
  3205.   sc2(force)(res_flag+p)(close);
  3206.   end; {\&{end}}
  3207. if_like: begin sc0(cond); sc2(force)(res_flag+p)(alpha);
  3208.   end; {\&{if}}
  3209. loop_like: begin sc3(force)("\")("~")(alpha);
  3210. @.\\\~@>
  3211.   sc1(res_flag+p)(omega);
  3212.   end; {\&{xclause}}
  3213. proc_like: begin sc4(force)(backup)(res_flag+p)(cancel)(proc);
  3214.   sc3(indent)("\")(" ")(intro);
  3215. @.\\\ @>
  3216.   end; {\&{function}, \&{procedure}, \&{program}}
  3217. record_like: begin sc1(res_flag+p)(record_head); sc0(intro);
  3218.   end; {\&{record}}
  3219. repeat_like: begin sc4(force)(indent)(res_flag+p)(cancel)(beginning);
  3220.   sc0(intro);
  3221.   end; {\&{repeat}}
  3222. until_like: begin @<Append |term...@>;
  3223.   sc3(force)(backup)(res_flag+p)(close); sc0(clause);
  3224.   end; {\&{until}}
  3225. var_like: begin sc4(force)(backup)(res_flag+p)(cancel)(var_head); sc0(intro);
  3226.   end; {\&{var}}
  3227. @ If a comment or semicolon appears before the reserved words \&{end},
  3228. \&{else}, or \&{until}, the |semi| or |terminator| scrap that is already
  3229. present overrides the |terminator| scrap belonging to this reserved word.
  3230. @<Append |termin...@>=
  3231. if (scrap_ptr<scrap_base)or((cat[scrap_ptr]<>terminator)and
  3232.     (cat[scrap_ptr]<>semi)) then sc0(terminator)
  3233. @ A comment is incorporated into the previous scrap if that scrap is of type
  3234. |omega| or |semi| or |terminator|. (These three categories have consecutive
  3235. category codes.) Otherwise the comment is entered as a separate scrap
  3236. of type |terminator|, and it will combine with a |terminator| scrap that
  3237. immediately follows~it.
  3238. The |app_comment| procedure takes care of placing a comment at the end of the
  3239. current scrap list. When |app_comment| is called, we assume that the current
  3240. token list is the translation of the comment involved.
  3241. @<Declaration of the |app_comment|...@>=
  3242. procedure app_comment; {append a comment to the scrap list}
  3243. begin freeze_text;
  3244. if (scrap_ptr<scrap_base)or(cat[scrap_ptr]<omega)or
  3245.     (cat[scrap_ptr]>terminator) then sc0(terminator)
  3246. else  begin app1(scrap_ptr); {|cat[scrap_ptr]| is
  3247.     |omega| or |semi| or |terminator|}
  3248.   end;
  3249. app(text_ptr-1+tok_flag); trans[scrap_ptr]:=text_ptr; freeze_text;
  3250. @ We are now finished with |Pascal_parse|, except for two relatively
  3251. trivial subprocedures that convert constants into tokens.
  3252. @<Declaration of the |app_octal| and...@>=
  3253. procedure app_octal;
  3254. begin app("\"); app("O"); app("{");
  3255. @.\\O@>
  3256. while (buffer[loc]>="0")and(buffer[loc]<="7") do
  3257.   begin app_tok(buffer[loc]); incr(loc);
  3258.   end;
  3259. sc1("}")(simp);
  3260. procedure app_hex;
  3261. begin app("\"); app("H"); app("{");
  3262. @.\\H@>
  3263. while ((buffer[loc]>="0")and(buffer[loc]<="9"))or@|
  3264.     ((buffer[loc]>="A")and(buffer[loc]<="F")) do
  3265.   begin app_tok(buffer[loc]); incr(loc);
  3266.   end;
  3267. sc1("}")(simp);
  3268. @ When the `\v' that introduces \PASCAL\ text is sensed, a call on
  3269. |Pascal_translate| will return a pointer to the \TeX\ translation of
  3270. that text. If scraps exist in the |cat| and |trans| arrays, they are
  3271. unaffected by this translation process.
  3272. @p function Pascal_translate: text_pointer;
  3273. var p:text_pointer; {points to the translation}
  3274. @!save_base:0..max_scraps; {holds original value of |scrap_base|}
  3275. begin save_base:=scrap_base; scrap_base:=scrap_ptr+1;
  3276. Pascal_parse; {get the scraps together}
  3277. if next_control<>"|" then err_print('! Missing "|" after Pascal text');
  3278. @.Missing "|"...@>
  3279. app_tok(cancel); app_comment; {place a |cancel| token as a final ``comment''}
  3280. p:=translate; {make the translation}
  3281. stat if scrap_ptr>max_scr_ptr then max_scr_ptr:=scrap_ptr;@;@+tats@;@/
  3282. scrap_ptr:=scrap_base-1; scrap_base:=save_base; {scrap the scraps}
  3283. Pascal_translate:=p;
  3284. @ The |outer_parse| routine is to |Pascal_parse| as |outer_xref|
  3285. is to |Pascal_xref|: It constructs a sequence of scraps for \PASCAL\ text
  3286. until |next_control>=format|. Thus, it takes care of embedded comments.
  3287. @p procedure outer_parse; {makes scraps from \PASCAL\ tokens and comments}
  3288. var bal:eight_bits; {brace level in comment}
  3289. @!p,@!q:text_pointer; {partial comments}
  3290. begin while next_control<format do
  3291.   if next_control<>"{" then Pascal_parse
  3292.   else  begin @<Make sure that there is room for at least seven more
  3293.       tokens, three more texts, and one more scrap@>;
  3294.     app("\"); app("C"); app("{");
  3295. @.\\C@>
  3296.     bal:=copy_comment(1); next_control:="|";
  3297.     while bal>0 do
  3298.       begin p:=text_ptr; freeze_text; q:=Pascal_translate;
  3299.       {at this point we have |tok_ptr+6<=max_toks|}
  3300.       app(tok_flag+p); app(inner_tok_flag+q);
  3301.       if next_control="|" then bal:=copy_comment(bal)
  3302.       else bal:=0; {an error has been reported}
  3303.       end;
  3304.     app(force); app_comment; {the full comment becomes a scrap}
  3305.     end;
  3306. @ @<Make sure that there is room for at least seven more...@>=
  3307. if (tok_ptr+7>max_toks)or(text_ptr+3>max_texts)or(scrap_ptr>=max_scraps) then
  3308.   begin stat if scrap_ptr>max_scr_ptr then max_scr_ptr:=scrap_ptr;
  3309.   if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;
  3310.   if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  3311.   tats@;@/
  3312.   overflow('token/text/scrap');
  3313.   end
  3314. @* Output of tokens.
  3315. So far our programs have only built up multi-layered token lists in
  3316. \.{WEAVE}'s internal memory; we have to figure out how to get them into
  3317. the desired final form. The job of converting token lists to characters in
  3318. the \TeX\ output file is not difficult, although it is an implicitly
  3319. recursive process. Three main considerations had to be kept in mind when
  3320. this part of \.{WEAVE} was designed:  (a) There are two modes of output,
  3321. |outer| mode that translates tokens like |force| into line-breaking
  3322. control sequences, and |inner| mode that ignores them except that blank
  3323. spaces take the place of line breaks. (b) The |cancel| instruction applies
  3324. to adjacent token or tokens that are output, and this cuts across levels
  3325. of recursion since `|cancel|' occurs at the beginning or end of a token
  3326. list on one level. (c) The \TeX\ output file will be semi-readable if line
  3327. breaks are inserted after the result of tokens like |break_space| and
  3328. |force|.  (d) The final line break should be suppressed, and there should
  3329. be no |force| token output immediately after `\.{\\Y\\P}'.
  3330. @ The output process uses a stack to keep track of what is going on at
  3331. different ``levels'' as the token lists are being written out. Entries on
  3332. this stack have three parts:
  3333. \yskip\hang |end_field| is the |tok_mem| location where the token list of a
  3334. particular level will end;
  3335. \yskip\hang |tok_field| is the |tok_mem| location from which the next token
  3336. on a particular level will be read;
  3337. \yskip\hang |mode_field| is the current mode, either |inner| or |outer|.
  3338. \yskip\noindent The current values of these quantities are referred to
  3339. quite frequently, so they are stored in a separate place instead of in the
  3340. |stack| array. We call the current values |cur_end|, |cur_tok|, and
  3341. |cur_mode|.
  3342. The global variable |stack_ptr| tells how many levels of output are
  3343. currently in progress. The end of output occurs when an |end_translation|
  3344. token is found, so the stack is never empty except when we first begin the
  3345. output process.
  3346. @d inner=0 {value of |mode| for \PASCAL\ texts within \TeX\ texts}
  3347. @d outer=1 {value of |mode| for \PASCAL\ texts in modules}
  3348. @<Types...@>=
  3349. @!mode=inner..outer;@/
  3350. @!output_state=record@!end_field:sixteen_bits; {ending location of token list}
  3351.   @!tok_field:sixteen_bits; {present location within token list}
  3352.   @!mode_field:mode; {interpretation of control tokens}
  3353.   end;
  3354. @ @d cur_end==cur_state.end_field {current ending location in |tok_mem|}
  3355. @d cur_tok==cur_state.tok_field {location of next output token in |tok_mem|}
  3356. @d cur_mode==cur_state.mode_field {current mode of interpretation}
  3357. @d init_stack==stack_ptr:=0;cur_mode:=outer {do this to initialize the stack}
  3358. @<Glob...@>=
  3359. @!cur_state:output_state; {|cur_end|, |cur_tok|, |cur_mode|}
  3360. @!stack:array[1..stack_size] of output_state; {info for non-current levels}
  3361. @!stack_ptr:0..stack_size; {first unused location in the output state stack}
  3362. stat@!max_stack_ptr:0..stack_size; {largest value assumed by |stack_ptr|}
  3363. @ @<Set init...@>=stat max_stack_ptr:=0;@+tats
  3364. @ To insert token-list |p| into the output, the |push_level| subroutine
  3365. is called; it saves the old level of output and gets a new one going.
  3366. The value of |cur_mode| is not changed.
  3367. @p procedure push_level(@!p:text_pointer); {suspends the current level}
  3368. begin if stack_ptr=stack_size then overflow('stack')
  3369. else  begin if stack_ptr>0 then
  3370.     stack[stack_ptr]:=cur_state; {save |cur_end|$\,\ldots\,$|cur_mode|}
  3371.   incr(stack_ptr);
  3372.   stat if stack_ptr>max_stack_ptr then
  3373.     max_stack_ptr:=stack_ptr;@;@+tats@;@/
  3374.   cur_tok:=tok_start[p]; cur_end:=tok_start[p+1];
  3375.   end;
  3376. @ Conversely, the |pop_level| routine restores the conditions that were in
  3377. force when the current level was begun. This subroutine will never be
  3378. called when |stack_ptr=1|. It is so simple, we declare it as a macro:
  3379. @d pop_level==begin decr(stack_ptr); cur_state:=stack[stack_ptr];
  3380.   end {do this when |cur_tok| reaches |cur_end|}
  3381. @ The |get_output| function returns the next byte of output that is not a
  3382. reference to a token list. It returns the values |identifier| or |res_word|
  3383. or |mod_name| if the next token is to be an identifier (typeset in
  3384. italics), a reserved word (typeset in boldface) or a module name (typeset
  3385. by a complex routine that might generate additional levels of output).
  3386. In these cases |cur_name| points to the identifier or module name in
  3387. question.
  3388. @d res_word=@'201 {returned by |get_output| for reserved words}
  3389. @d mod_name=@'200 {returned by |get_output| for module names}
  3390. @p function get_output:eight_bits; {returns the next token of output}
  3391. label restart;
  3392. var a:sixteen_bits; {current item read from |tok_mem|}
  3393. begin restart: while cur_tok=cur_end do pop_level;
  3394. a:=tok_mem[cur_tok]; incr(cur_tok);
  3395. if a>=@'400 then
  3396.   begin cur_name:=a mod id_flag;
  3397.   case a div id_flag of
  3398.   2: a:=res_word; {|a=res_flag+cur_name|}
  3399.   3: a:=mod_name; {|a=mod_flag+cur_name|}
  3400.   4: begin push_level(cur_name); goto restart;
  3401.     end; {|a=tok_flag+cur_name|}
  3402.   5: begin push_level(cur_name); cur_mode:=inner; goto restart;
  3403.     end; {|a=inner_tok_flag+cur_name|}
  3404.   othercases a:=identifier {|a=id_flag+cur_name|}
  3405.   endcases;
  3406.   end;
  3407. @!debug if trouble_shooting then debug_help; @+ gubed@/
  3408. get_output:=a;
  3409. @ The real work associated with token output is done by |make_output|.
  3410. This procedure appends an |end_translation| token to the current token list,
  3411. and then it repeatedly calls |get_output| and feeds characters to the output
  3412. buffer until reaching the |end_translation| sentinel. It is possible for
  3413. |make_output| to
  3414. be called recursively, since a module name may include embedded \PASCAL\
  3415. text; however, the depth of recursion never exceeds one level, since
  3416. module names cannot be inside of module names.
  3417. A procedure called |output_Pascal| does the scanning, translation, and
  3418. output of \PASCAL\ text within `\pb' brackets, and this procedure uses
  3419. |make_output| to output the current token list. Thus, the recursive call
  3420. of |make_output| actually occurs when |make_output| calls |output_Pascal|
  3421. while outputting the name of a module.
  3422. @^recursion@>
  3423. @p procedure make_output; forward; @t\2@>@#
  3424. procedure output_Pascal; {outputs the current token list}
  3425. var save_tok_ptr,@!save_text_ptr,@!save_next_control:sixteen_bits;
  3426.   {values to be restored}
  3427. p:text_pointer; {translation of the \PASCAL\ text}
  3428. begin save_tok_ptr:=tok_ptr; save_text_ptr:=text_ptr;
  3429. save_next_control:=next_control; next_control:="|"; p:=Pascal_translate;
  3430. app(p+inner_tok_flag);
  3431. make_output; {output the list}
  3432. stat if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  3433. if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;@;@+tats@;@/
  3434. text_ptr:=save_text_ptr; tok_ptr:=save_tok_ptr; {forget the tokens}
  3435. next_control:=save_next_control; {restore |next_control| to original state}
  3436. @ Here is \.{WEAVE}'s major output handler.
  3437. @p procedure make_output; {outputs the equivalents of tokens}
  3438. label reswitch,exit,found;
  3439. var a:eight_bits; {current output byte}
  3440. @!b:eight_bits; {next output byte}
  3441. @!k,@!k_limit:0..max_bytes; {indices into |byte_mem|}
  3442. @!w:0..ww-1; {row of |byte_mem|}
  3443. @!j:0..long_buf_size; {index into |buffer|}
  3444. @!string_delimiter:ASCII_code; {first and last character of
  3445.   string being copied}
  3446. @!save_loc,@!save_limit:0..long_buf_size; {|loc| and |limit| to be restored}
  3447. @!cur_mod_name:name_pointer; {name of module being output}
  3448. @!save_mode:mode; {value of |cur_mode| before a sequence of breaks}
  3449. begin app(end_translation); {append a sentinel}
  3450. freeze_text; push_level(text_ptr-1);
  3451. loop@+  begin a:=get_output;
  3452. reswitch: case a of
  3453.   end_translation: return;
  3454.   identifier,res_word:@<Output an identifier@>;
  3455.   mod_name:@<Output a module name@>;
  3456.   math_bin,math_op,math_rel:@<Output a \.{\\math} operator@>;
  3457.   cancel: begin repeat a:=get_output;
  3458.     until (a<backup)or(a>big_force);
  3459.     goto reswitch;
  3460.     end;
  3461.   big_cancel: begin repeat a:=get_output;
  3462.     until ((a<backup)and(a<>" "))or(a>big_force);
  3463.     goto reswitch;
  3464.     end;
  3465.   indent,outdent,opt,backup,break_space,force,big_force:@<Output a
  3466.     \(control, look ahead in case of line breaks,
  3467.     possibly |goto reswitch|@>;
  3468.   othercases out(a) {otherwise |a| is an ASCII character}
  3469.   endcases;
  3470.   end;
  3471. exit:end;
  3472. @ An identifier of length one does not have to be enclosed in braces, and it
  3473. looks slightly better if set in a math-italic font instead of a (slightly
  3474. narrower) text-italic font. Thus we output `\.{\\\char'174a}' but
  3475. `\.{\\\\\{aa\}}'.
  3476. @<Output an identifier@>=
  3477. begin out("\");
  3478. if a=identifier then
  3479.   if length(cur_name)=1 then out("|")
  3480. @.\\|@>
  3481.   else out("\")
  3482. @.\\\\@>
  3483. else out("&"); {|a=res_word|}
  3484. @.\\\&@>
  3485. if length(cur_name)=1 then out(byte_mem[cur_name mod ww,byte_start[cur_name]])
  3486. else out_name(cur_name);
  3487. @ @<Output a \....@>=
  3488. begin out5("\")("m")("a")("t")("h");
  3489. if a=math_bin then out3("b")("i")("n")
  3490. else if a=math_rel then out3("r")("e")("l")
  3491. else out2("o")("p");
  3492. out("{");
  3493. @ The current mode does not affect the behavior of \.{WEAVE}'s output routine
  3494. except when we are outputting control tokens.
  3495. @<Output a \(control...@>=
  3496. if a<break_space then
  3497.   begin if cur_mode=outer then
  3498.     begin out2("\")(a-cancel+"0");
  3499. @.\\1@>
  3500. @.\\2@>
  3501. @.\\3@>
  3502. @.\\4@>
  3503. @.\\5@>
  3504. @.\\6@>
  3505. @.\\7@>
  3506.     if a=opt then out(get_output) {|opt| is followed by a digit}
  3507.     end
  3508.   else if a=opt then b:=get_output {ignore digit following |opt|}
  3509.   end
  3510. else @<Look ahead for strongest line break, |goto reswitch|@>
  3511. @ If several of the tokens |break_space|, |force|, |big_force| occur in a
  3512. row, possibly mixed with blank spaces (which are ignored),
  3513. the largest one is used. A line break also occurs in the output file,
  3514. except at the very end of the translation. The very first line break
  3515. is suppressed (i.e., a line break that follows `\.{\\Y\\P}').
  3516. @<Look ahead for st...@>=
  3517. begin b:=a; save_mode:=cur_mode;
  3518. loop@+  begin a:=get_output;
  3519.   if (a=cancel)or(a=big_cancel) then goto reswitch;
  3520.     {|cancel| overrides everything}
  3521.   if ((a<>" ")and(a<break_space))or(a>big_force) then
  3522.     begin if save_mode=outer then
  3523.       begin if out_ptr>3 then
  3524.         if (out_buf[out_ptr]="P")and
  3525.           (out_buf[out_ptr-1]="\")and
  3526. @.\\P@>
  3527. @.\\Y@>
  3528.           (out_buf[out_ptr-2]="Y")and
  3529.           (out_buf[out_ptr-3]="\") then
  3530.           goto reswitch;
  3531. @.\\1@>
  3532. @.\\2@>
  3533. @.\\3@>
  3534. @.\\4@>
  3535. @.\\5@>
  3536. @.\\6@>
  3537. @.\\7@>
  3538.       out2("\")(b-cancel+"0");
  3539.       if a<>end_translation then finish_line;
  3540.       end
  3541.     else if (a<>end_translation)and(cur_mode=inner) then out(" ");
  3542.     goto reswitch;
  3543.     end;
  3544.   if a>b then b:=a; {if |a=" "| we have |a<b|}
  3545.   end;
  3546. @ The remaining part of |make_output| is somewhat more complicated. When we
  3547. output a module name, we may need to enter the parsing and translation
  3548. routines, since the name may contain \PASCAL\ code embedded in
  3549. \pb\ constructions. This \PASCAL\ code is placed at the end of the active
  3550. input buffer and the translation process uses the end of the active
  3551. |tok_mem| area.
  3552. @<Output a module name@>=
  3553. begin out2("\")("X");
  3554. @.\\X@>
  3555. cur_xref:=xref[cur_name];
  3556. if num(cur_xref)>=def_flag then
  3557.   begin out_mod(num(cur_xref)-def_flag);
  3558.   if phase_three then
  3559.     begin cur_xref:=xlink(cur_xref);
  3560.     while num(cur_xref)>=def_flag do
  3561.       begin out2(",")(" ");
  3562.       out_mod(num(cur_xref)-def_flag);
  3563.       cur_xref:=xlink(cur_xref);
  3564.       end;
  3565.     end;
  3566.   end
  3567. else out("0"); {output the module number, or zero if it was undefined}
  3568. out(":"); @<Output the text of the module name@>;
  3569. out2("\")("X");
  3570. @ @<Output the text...@>=
  3571. k:=byte_start[cur_name]; w:=cur_name mod ww; k_limit:=byte_start[cur_name+ww];
  3572. cur_mod_name:=cur_name;
  3573. while k<k_limit do
  3574.   begin b:=byte_mem[w,k]; incr(k);
  3575.   if b="@@" then @<Skip next character, give error if not `\.{@@}'@>;
  3576.   if b<>"|" then out(b)
  3577.   else  begin @<Copy the \PASCAL\ text into |buffer[(limit+1)..j]|@>;
  3578.     save_loc:=loc; save_limit:=limit; loc:=limit+2; limit:=j+1;
  3579.     buffer[limit]:="|"; output_Pascal;
  3580.     loc:=save_loc; limit:=save_limit;
  3581.     end;
  3582.   end
  3583. @ @<Skip next char...@>=
  3584. begin if byte_mem[w,k]<>"@@" then
  3585.   begin print_nl('! Illegal control code in section name:');
  3586. @.Illegal control code...@>
  3587.   print_nl('<'); print_id(cur_mod_name); print('> '); mark_error;
  3588.   end;
  3589. incr(k);
  3590. @ The \PASCAL\ text enclosed in \pb\ should not contain `\v' characters,
  3591. except within strings. We put a `\v' at the front of the buffer, so that an
  3592. error message that displays the whole buffer will look a little bit sensible.
  3593. The variable |string_delimiter| is zero outside of strings, otherwise it
  3594. equals the delimiter that began the string being copied.
  3595. @<Copy the \PASCAL\ text into...@>=
  3596. j:=limit+1; buffer[j]:="|"; string_delimiter:=0;
  3597. loop@+  begin if k>=k_limit then
  3598.     begin print_nl('! Pascal text in section name didn''t end:');
  3599. @.Pascal text...didn't end@>
  3600.     print_nl('<'); print_id(cur_mod_name); print('> '); mark_error;
  3601.     goto found;
  3602.     end;
  3603.   b:=byte_mem[w,k]; incr(k);
  3604.   if b="@@" then @<Copy a control code into the buffer@>
  3605.   else  begin if (b="""")or(b="'") then
  3606.       if string_delimiter=0 then string_delimiter:=b
  3607.       else if string_delimiter=b then string_delimiter:=0;
  3608.     if (b<>"|")or(string_delimiter<>0) then
  3609.       begin if j>long_buf_size-3 then overflow('buffer');
  3610.       incr(j); buffer[j]:=b;
  3611.       end
  3612.     else goto found;
  3613.     end;
  3614.   end;
  3615. found:
  3616. @ @<Copy a control code into the buffer@>=
  3617. begin if j>long_buf_size-4 then overflow('buffer');
  3618. buffer[j+1]:="@@"; buffer[j+2]:=byte_mem[w,k]; j:=j+2; incr(k);
  3619. @* Phase two processing.
  3620. We have assembled enough pieces of the puzzle in order to be ready to specify
  3621. the processing in \.{WEAVE}'s main pass over the source file. Phase two
  3622. is analogous to phase one, except that more work is involved because we must
  3623. actually output the \TeX\ material instead of merely looking at the
  3624. \.{WEB} specifications.
  3625. @<Phase II: Read all the text again and translate it to \TeX\ form@>=
  3626. reset_input; print_nl('Writing the output file...');
  3627. module_count:=0;
  3628. copy_limbo;
  3629. finish_line; flush_buffer(0,false); {insert a blank line, it looks nice}
  3630. while not input_has_ended do @<Translate the \(current module@>
  3631. @ The output file will contain the control sequence \.{\\Y} between non-null
  3632. sections of a module, e.g., between the \TeX\ and definition parts if both
  3633. are nonempty. This puts a little white space between the parts when they are
  3634. printed. However, we don't want \.{\\Y} to occur between two definitions
  3635. within a single module. The variables |out_line| or |out_ptr| will
  3636. change if a section is non-null, so the following macros `|save_position|'
  3637. and `|emit_space_if_needed|' are able to handle the situation:
  3638. @d save_position==save_line:=out_line; save_place:=out_ptr
  3639. @d emit_space_if_needed==if (save_line<>out_line)or(save_place<>out_ptr) then
  3640.   out2("\")("Y")
  3641. @.\\Y@>
  3642. @<Glo...@>=
  3643. @!save_line:integer; {former value of |out_line|}
  3644. @!save_place:sixteen_bits; {former value of |out_ptr|}
  3645. @ @<Translate the \(current module@>=
  3646. begin incr(module_count);@/
  3647. @<Output the code for the beginning of a new module@>;
  3648. save_position;@/
  3649. @<Translate the \TeX\ part of the current module@>;
  3650. @<Translate the \(definition part of the current module@>;
  3651. @<Translate the \PASCAL\ part of the current module@>;
  3652. @<Show cross references to this module@>;
  3653. @<Output the code for the end of a module@>;
  3654. @ Modules beginning with the \.{WEB} control sequence `\.{@@\ }' start in the
  3655. output with the \TeX\ control sequence `\.{\\M}', followed by the module
  3656. number. Similarly, `\.{@@*}' modules lead to the control sequence `\.{\\N}'.
  3657. If this is a changed module, we put \.{*} just before the module number.
  3658. @<Output the code for the beginning...@>=
  3659. out("\");
  3660. if buffer[loc-1]<>"*" then out("M")
  3661. @.\\M@>
  3662. else  begin out("N"); print('*',module_count:1);
  3663. @.\\N@>
  3664.   update_terminal; {print a progress report}
  3665.   end;
  3666. out_mod(module_count); out2(".")(" ")
  3667. @ In the \TeX\ part of a module, we simply copy the source text, except that
  3668. index entries are not copied and \PASCAL\ text within \pb\ is translated.
  3669. @<Translate the \T...@>=
  3670. repeat next_control:=copy_TeX;
  3671. case next_control of
  3672. "|": begin init_stack; output_Pascal;
  3673.   end;
  3674. "@@": out("@@");
  3675. octal: @<Translate an octal constant appearing in \TeX\ text@>;
  3676. hex: @<Translate a hexadecimal constant appearing in \TeX\ text@>;
  3677. TeX_string,xref_roman,xref_wildcard,xref_typewriter,module_name:
  3678.   begin loc:=loc-2; next_control:=get_next; {skip to \.{@@>}}
  3679.   if next_control=TeX_string then
  3680.     err_print('! TeX string should be in Pascal text only');
  3681. @.TeX string should be...@>
  3682.   end;
  3683. begin_comment,end_comment,check_sum,thin_space,math_break,line_break,
  3684.   big_line_break,no_line_break,join,pseudo_semi:
  3685.     err_print('! You can''t do that in TeX text');
  3686. @.You can't do that...@>
  3687. othercases do_nothing
  3688. endcases;
  3689. until next_control>=format
  3690. @ @<Translate an octal constant appearing in \TeX\ text@>=
  3691. begin out3("\")("O")("{");
  3692. @.\\O@>
  3693. while (buffer[loc]>="0")and(buffer[loc]<="7") do
  3694.   begin out(buffer[loc]); incr(loc);
  3695.   end; {since |buffer[limit]=" "|, this loop will end}
  3696. out("}");
  3697. @ @<Translate a hexadecimal constant appearing in \TeX\ text@>=
  3698. begin out3("\")("H")("{");
  3699. @.\\H@>
  3700. while ((buffer[loc]>="0")and(buffer[loc]<="9"))or@|
  3701.     ((buffer[loc]>="A")and(buffer[loc]<="F")) do
  3702.   begin out(buffer[loc]); incr(loc);
  3703.   end;
  3704. out("}");
  3705. @ When we get to the following code we have |next_control>=format|, and
  3706. the token memory is in its initial empty state.
  3707. @<Translate the \(d...@>=
  3708. if next_control<=definition then {definition part non-empty}
  3709.   begin emit_space_if_needed; save_position;
  3710.   end;
  3711. while next_control<=definition do {|format| or |definition|}
  3712.   begin init_stack;
  3713.   if next_control=definition then @<Start a macro definition@>
  3714.   else @<Start a format definition@>;
  3715.   outer_parse; finish_Pascal;
  3716.   end
  3717. @ The |finish_Pascal| procedure outputs the translation of the current
  3718. scraps, preceded by the control sequence `\.{\\P}' and followed by the
  3719. control sequence `\.{\\par}'. It also restores the token and scrap
  3720. memories to their initial empty state.
  3721. A |force| token is appended to the current scraps before translation
  3722. takes place, so that the translation will normally end with \.{\\6} or
  3723. \.{\\7} (the \TeX\ macros for |force| and |big_force|). This \.{\\6} or
  3724. \.{\\7} is replaced by the concluding \.{\\par} or by \.{\\Y\\par}.
  3725. @p procedure finish_Pascal; {finishes a definition or a \PASCAL\ part}
  3726. var p:text_pointer; {translation of the scraps}
  3727. begin out2("\")("P"); app_tok(force); app_comment; p:=translate;
  3728. @.\\P@>
  3729. app(p+tok_flag); make_output; {output the list}
  3730. if out_ptr>1 then
  3731.   if out_buf[out_ptr-1]="\" then
  3732. @.\\6@>
  3733. @.\\7@>
  3734. @.\\Y@>
  3735.     if out_buf[out_ptr]="6" then out_ptr:=out_ptr-2
  3736.     else if out_buf[out_ptr]="7" then out_buf[out_ptr]:="Y";
  3737. out4("\")("p")("a")("r"); finish_line;
  3738. stat if text_ptr>max_txt_ptr then max_txt_ptr:=text_ptr;
  3739. if tok_ptr>max_tok_ptr then max_tok_ptr:=tok_ptr;
  3740. if scrap_ptr>max_scr_ptr then max_scr_ptr:=scrap_ptr;
  3741. tats@;@/
  3742. tok_ptr:=1; text_ptr:=1; scrap_ptr:=0; {forget the tokens and the scraps}
  3743. @ @<Start a macro...@>=
  3744. begin sc2("\")("D")(intro); {this will produce `\&{define }'}
  3745. @.\\D@>
  3746. next_control:=get_next;
  3747. if next_control<>identifier then err_print('! Improper macro definition')
  3748. @.Improper macro definition@>
  3749. else sc1(id_flag+id_lookup(normal))(math);
  3750. next_control:=get_next;
  3751. @ @<Start a format...@>=
  3752. begin sc2("\")("F")(intro); {this will produce `\&{format }'}
  3753. @.\\F@>
  3754. next_control:=get_next;
  3755. if next_control=identifier then
  3756.   begin sc1(id_flag+id_lookup(normal))(math);
  3757.   next_control:=get_next;
  3758.   if next_control=equivalence_sign then
  3759.     begin sc2("\")("S")(math); {output an equivalence sign}
  3760. @.\\S@>
  3761.     next_control:=get_next;
  3762.     if next_control=identifier then
  3763.       begin sc1(id_flag+id_lookup(normal))(math);
  3764.       sc0(semi); {insert an invisible semicolon}
  3765.       next_control:=get_next;
  3766.       end;
  3767.     end;
  3768.   end;
  3769. if scrap_ptr<>5 then err_print('! Improper format definition');
  3770. @.Improper format definition@>
  3771. @ Finally, when the \TeX\ and definition parts have been treated, we have
  3772. |next_control>=begin_Pascal|. We will make the global variable |this_module|
  3773. point to the current module name, if it has a name.
  3774. @<Glob...@>=@!this_module:name_pointer; {the current module name, or zero}
  3775. @ @<Translate the \P...@>=
  3776. this_module:=0;
  3777. if next_control<=module_name then
  3778.   begin emit_space_if_needed; init_stack;
  3779.   if next_control=begin_Pascal then next_control:=get_next
  3780.   else  begin this_module:=cur_module;
  3781.     @<Check that |=| or |==| follows this module name, and
  3782.       emit the scraps to start the module definition@>;
  3783.     end;
  3784.   while next_control<=module_name do
  3785.     begin outer_parse;
  3786.     @<Emit the scrap for a module name if present@>;
  3787.     end;
  3788.   finish_Pascal;
  3789.   end
  3790. @ @<Check that |=|...@>=
  3791. repeat next_control:=get_next;
  3792. until next_control<>"+"; {allow optional `\.{+=}'}
  3793. if (next_control<>"=")and(next_control<>equivalence_sign) then
  3794.   err_print('! You need an = sign after the section name')
  3795. @.You need an = sign...@>
  3796. else next_control:=get_next;
  3797. if out_ptr>1 then
  3798.   if (out_buf[out_ptr]="Y")and(out_buf[out_ptr-1]="\") then
  3799. @.\\Y@>
  3800.     begin app(backup); {the module name will be flush left}
  3801.     end;
  3802. sc1(mod_flag+this_module)(mod_scrap);
  3803. cur_xref:=xref[this_module];
  3804. if num(cur_xref)<>module_count+def_flag then
  3805.   begin sc3(math_rel)("+")("}")(math);
  3806.     {module name is multiply defined}
  3807.   this_module:=0; {so we won't give cross-reference info here}
  3808.   end;
  3809. sc2("\")("S")(math); {output an equivalence sign}
  3810. @.\\S@>
  3811. sc1(force)(semi); {this forces a line break unless `\.{@@+}' follows}
  3812. @ @<Emit the scrap...@>=
  3813. if next_control<module_name then
  3814.   begin err_print('! You can''t do that in Pascal text');
  3815. @.You can't do that...@>
  3816.   next_control:=get_next;
  3817.   end
  3818. else if next_control=module_name then
  3819.   begin sc1(mod_flag+cur_module)(mod_scrap); next_control:=get_next;
  3820.   end
  3821. @ Cross references relating to a named module are given after the module ends.
  3822. @<Show cross...@>=
  3823. if this_module>0 then
  3824.   begin @<Rearrange the list pointed to by |cur_xref|@>;
  3825.   footnote(def_flag); footnote(0);
  3826.   end
  3827. @ To rearrange the order of the linked list of cross references, we need
  3828. four more variables that point to cross reference entries.  We'll end up
  3829. with a list pointed to by |cur_xref|.
  3830. @<Glob...@>=
  3831. @!next_xref,@!this_xref,@!first_xref,@!mid_xref:xref_number;
  3832.   {pointer variables for rearranging a list}
  3833. @ We want to rearrange the cross reference list so that all the entries with
  3834. |def_flag| come first, in ascending order; then come all the other
  3835. entries, in ascending order.  There may be no entries in either one or both
  3836. of these categories.
  3837. @<Rearrange the list...@>=
  3838. first_xref:=xref[this_module];
  3839. this_xref:=xlink(first_xref); {bypass current module number}
  3840. if num(this_xref)>def_flag then
  3841.   begin mid_xref:=this_xref; cur_xref:=0; {this value doesn't matter}
  3842.   repeat  next_xref:=xlink(this_xref); xlink(this_xref):=cur_xref;
  3843.     cur_xref:=this_xref; this_xref:=next_xref;
  3844.   until num(this_xref)<=def_flag;
  3845.   xlink(first_xref):=cur_xref;
  3846.   end
  3847. else mid_xref:=0; {first list null}
  3848. cur_xref:=0;
  3849. while this_xref<>0 do
  3850.   begin next_xref:=xlink(this_xref); xlink(this_xref):=cur_xref;
  3851.   cur_xref:=this_xref; this_xref:=next_xref;
  3852.   end;
  3853. if mid_xref>0 then xlink(mid_xref):=cur_xref
  3854. else xlink(first_xref):=cur_xref;
  3855. cur_xref:=xlink(first_xref)
  3856. @ The |footnote| procedure gives cross reference information about
  3857. multiply defined module names (if the |flag| parameter is |def_flag|), or about
  3858. the uses of a module name (if the |flag| parameter is zero). It assumes that
  3859. |cur_xref| points to the first cross-reference entry of interest, and it
  3860. leaves |cur_xref| pointing to the first element not printed.  Typical outputs:
  3861. `\.{\\A\ section 101.}'; `\.{\\U\ sections 370 and 1009.}';
  3862. `\.{\\A\ sections 8, 27\\*, and 64.}'.
  3863. @p procedure footnote(@!flag:sixteen_bits); {outputs module cross-references}
  3864. label done,exit;
  3865. var q:xref_number; {cross-reference pointer variable}
  3866. begin if num(cur_xref)<=flag then return;
  3867. finish_line; out("\");
  3868. @.\\A@>
  3869. @.\\U@>
  3870. if flag=0 then out("U")@+else out("A");
  3871. out4(" ")("s")("e")("c"); out4("t")("i")("o")("n");
  3872. @<Output all the module numbers on the reference list |cur_xref|@>;
  3873. out(".");
  3874. exit:end;
  3875. @ The following code distinguishes three cases, according as the number
  3876. of cross references is one, two, or more than two. Variable |q| points
  3877. to the first cross reference, and the last link is a zero.
  3878. @<Output all the module numbers...@>=
  3879. q:=cur_xref; if num(xlink(q))>flag then out("s"); {plural}
  3880. out("~");
  3881. loop@+  begin out_mod(num(cur_xref)-flag);
  3882.   cur_xref:=xlink(cur_xref); {point to the next cross reference to output}
  3883.   if num(cur_xref)<=flag then goto done;
  3884.   if (num(xlink(cur_xref))>flag)or(cur_xref<>xlink(q)) then out(",");
  3885.     {not the last of two}
  3886.   out(" ");
  3887.   if num(xlink(cur_xref))<=flag then out4("a")("n")("d")("~"); {the last}
  3888.   end;
  3889. done:
  3890. @ @<Output the code for the end of a module@>=
  3891. out3("\")("f")("i"); finish_line;
  3892. flush_buffer(0,false); {insert a blank line, it looks nice}
  3893. @.\\fi@>
  3894. @* Phase three processing.
  3895. We are nearly finished! \.{WEAVE}'s only remaining task is to write out the
  3896. index, after sorting the identifiers and index entries.
  3897. @<Phase III: Output the cross-reference index@>=
  3898. phase_three:=true; print_nl('Writing the index...');
  3899. if change_exists then
  3900.   begin finish_line; @<Tell about changed modules@>;
  3901.   end;
  3902. finish_line; out4("\")("i")("n")("x"); finish_line;
  3903. @.\\inx@>
  3904. @<Do the first pass of sorting@>;
  3905. @<Sort and output the index@>;
  3906. out4("\")("f")("i")("n"); finish_line;
  3907. @.\\fin@>
  3908. @<Output all the module names@>;
  3909. out4("\")("c")("o")("n"); finish_line;
  3910. @.\\con@>
  3911. print('Done.');
  3912. @ Just before the index comes a list of all the changed modules, including
  3913. the index module itself.
  3914. @<Glob...@>=
  3915. @!k_module:0..max_modules; {runs through the modules}
  3916. @ @<Tell about changed modules@>=
  3917. begin {remember that the index is already marked as changed}
  3918. k_module:=1;
  3919. out4("\")("c")("h")(" ");
  3920. while k_module<module_count do
  3921.   begin if changed_module[k_module] then
  3922.     begin out_mod(k_module); out2(",")(" ");
  3923.     end;
  3924.   incr(k_module);
  3925.   end;
  3926. out_mod(k_module);
  3927. out(".");
  3928. @ A left-to-right radix sorting method is used, since this makes it easy to
  3929. adjust the collating sequence and since the running time will be at worst
  3930. proportional to the total length of all entries in the index. We put the
  3931. identifiers into 230 different lists based on their first characters.
  3932. (Uppercase letters are put into the same list as the corresponding lowercase
  3933. letters, since we want to have `$t<\\{TeX}<\&{to}$'.) The
  3934. list for character |c| begins at location |bucket[c]| and continues through
  3935. the |blink| array.
  3936. @<Glob...@>=
  3937. @!bucket:array[ASCII_code] of name_pointer;
  3938. @!next_name: name_pointer; {successor of |cur_name| when sorting}
  3939. @!c:ASCII_code; {index into |bucket|}
  3940. @!h:0..hash_size; {index into |hash|}
  3941. @!blink:array[0..max_names] of sixteen_bits; {links in the buckets}
  3942. @ To begin the sorting, we go through all the hash lists and put each entry
  3943. having a nonempty cross-reference list into the proper bucket.
  3944. @<Do the first pass...@>=
  3945. for c:=0 to 255 do bucket[c]:=0;
  3946. for h:=0 to hash_size-1 do
  3947.   begin next_name:=hash[h];
  3948.   while next_name<>0 do
  3949.     begin cur_name:=next_name; next_name:=link[cur_name];
  3950.     if xref[cur_name]<>0 then
  3951.       begin c:=byte_mem[cur_name mod ww,byte_start[cur_name]];
  3952.       if (c<="Z")and(c>="A") then c:=c+@'40;
  3953.       blink[cur_name]:=bucket[c]; bucket[c]:=cur_name;
  3954.       end;
  3955.     end;
  3956.   end
  3957. @ During the sorting phase we shall use the |cat| and |trans| arrays from
  3958. \.{WEAVE}'s parsing algorithm and rename them |depth| and |head|. They now
  3959. represent a stack of identifier lists for all the index entries that have
  3960. not yet been output. The variable |sort_ptr| tells how many such lists are
  3961. present; the lists are output in reverse order (first |sort_ptr|, then
  3962. |sort_ptr-1|, etc.). The |j|th list starts at |head[j]|, and if the first
  3963. |k| characters of all entries on this list are known to be equal we have
  3964. |depth[j]=k|.
  3965. @d depth==cat {reclaims memory that is no longer needed for parsing}
  3966. @d head==trans {ditto}
  3967. @d sort_ptr==scrap_ptr {ditto}
  3968. @d max_sorts==max_scraps {ditto}
  3969. @<Globals...@>=
  3970. @!cur_depth:eight_bits; {depth of current buckets}
  3971. @!cur_byte:0..max_bytes; {index into |byte_mem|}
  3972. @!cur_bank:0..ww-1; {row of |byte_mem|}
  3973. @!cur_val:sixteen_bits; {current cross reference number}
  3974. stat@!max_sort_ptr:0..max_sorts;@+tats {largest value of |sort_ptr|}
  3975. @ @<Set init...@>=stat max_sort_ptr:=0;@+tats
  3976. @ The desired alphabetic order is specified by the |collate| array; namely,
  3977. |collate[0]<collate[1]<@t$\cdots$@><collate[229]|.
  3978. @<Glob...@>=@!collate:array[0..229] of ASCII_code; {collation order}
  3979. @ @<Local variables for init...@>=
  3980. @!c:ASCII_code; {used to initialize |collate|}
  3981. @ We use the order $\hbox{null}<\.\ <\hbox{other characters}<\.\_<
  3982. \.A=\.a<\cdots<\.Z=\.z<\.0<\cdots<\.9.$
  3983. @<Set init...@>=
  3984. collate[0]:=0; collate[1]:=" ";
  3985. for c:=1 to " "-1 do collate[c+1]:=c;
  3986. for c:=" "+1 to "0"-1 do collate[c]:=c;
  3987. for c:="9"+1 to "A"-1 do collate[c-10]:=c;
  3988. for c:="Z"+1 to "_"-1 do collate[c-36]:=c;
  3989. collate["_"-36]:="_"+1;
  3990. for c:="z"+1 to 255 do collate[c-63]:=c;
  3991. collate[193]:="_";
  3992. for c:="a" to "z" do collate[c-"a"+194]:=c;
  3993. for c:="0" to "9" do collate[c-"0"+220]:=c;
  3994. @ Procedure |unbucket| goes through the buckets and adds nonempty lists
  3995. to the stack, using the collating sequence specified in the |collate| array.
  3996. The parameter to |unbucket| tells the current depth in the buckets.
  3997. Any two sequences that agree in their first 255 character positions are
  3998. regarded as identical.
  3999. @d infinity=255 {$\infty$ (approximately)}
  4000. @p procedure unbucket(@!d:eight_bits); {empties buckets having depth |d|}
  4001. var c:ASCII_code; {index into |bucket|}
  4002. begin for c:=229 downto 0 do if bucket[collate[c]]>0 then
  4003.   begin if sort_ptr>max_sorts then overflow('sorting');
  4004.   incr(sort_ptr);
  4005.   stat if sort_ptr>max_sort_ptr then max_sort_ptr:=sort_ptr;@;@+tats@;@/
  4006.   if c=0 then depth[sort_ptr]:=infinity else depth[sort_ptr]:=d;
  4007.   head[sort_ptr]:=bucket[collate[c]]; bucket[collate[c]]:=0;
  4008.   end;
  4009. @ @<Sort and output...@>=
  4010. sort_ptr:=0; unbucket(1);
  4011. while sort_ptr>0 do
  4012.   begin cur_depth:=cat[sort_ptr];
  4013.   if (blink[head[sort_ptr]]=0)or(cur_depth=infinity) then
  4014.     @<Output index entries for the list at |sort_ptr|@>
  4015.   else @<Split the list at |sort_ptr| into further lists@>;
  4016.   end
  4017. @ @<Split the list...@>=
  4018. begin next_name:=head[sort_ptr];
  4019. repeat cur_name:=next_name; next_name:=blink[cur_name];
  4020.   cur_byte:=byte_start[cur_name]+cur_depth; cur_bank:=cur_name mod ww;
  4021.   if cur_byte=byte_start[cur_name+ww] then c:=0 {we hit the end of the name}
  4022.   else  begin c:=byte_mem[cur_bank,cur_byte];
  4023.     if (c<="Z")and(c>="A") then c:=c+@'40;
  4024.     end;
  4025.   blink[cur_name]:=bucket[c]; bucket[c]:=cur_name;
  4026. until next_name=0;
  4027. decr(sort_ptr); unbucket(cur_depth+1);
  4028. @ @<Output index...@>=
  4029. begin cur_name:=head[sort_ptr];
  4030. @!debug if trouble_shooting then debug_help;@;@+gubed@/
  4031. repeat out2("\")(":");
  4032. @.\\:@>
  4033.   @<Output the name at |cur_name|@>;
  4034.   @<Output the cross-references at |cur_name|@>;
  4035.   cur_name:=blink[cur_name];
  4036. until cur_name=0;
  4037. decr(sort_ptr);
  4038. @ @<Output the name...@>=
  4039. case ilk[cur_name] of
  4040. normal: if length(cur_name)=1 then out2("\")("|")@+else out2("\")("\");
  4041. @.\\|@>
  4042. @.\\\\@>
  4043. roman: do_nothing;
  4044. wildcard: out2("\")("9");
  4045. @.\\9@>
  4046. typewriter: out2("\")(".");
  4047. @.\\.@>
  4048. othercases out2("\")("&")
  4049. @.\\\&@>
  4050. endcases;@/
  4051. out_name(cur_name)
  4052. @ Section numbers that are to be underlined are enclosed in
  4053. `\.{\\[}$\,\ldots\,$\.]'.
  4054. @<Output the cross-references...@>=
  4055. @<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>;
  4056. repeat out2(",")(" "); cur_val:=num(cur_xref);
  4057. if cur_val<def_flag then out_mod(cur_val)
  4058. else  begin out2("\")("["); out_mod(cur_val-def_flag); out("]");
  4059. @.\\[@>
  4060.   end;
  4061. cur_xref:=xlink(cur_xref);
  4062. until cur_xref=0;
  4063. out("."); finish_line
  4064. @ List inversion is best thought of as popping elements off one stack and
  4065. pushing them onto another. In this case |cur_xref| will be the head of
  4066. the stack that we push things onto.
  4067. @<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>=
  4068. this_xref:=xref[cur_name]; cur_xref:=0;
  4069. repeat next_xref:=xlink(this_xref); xlink(this_xref):=cur_xref;
  4070. cur_xref:=this_xref; this_xref:=next_xref;
  4071. until this_xref=0
  4072. @ The following recursive procedure walks through the tree of module names and
  4073. prints them.
  4074. @^recursion@>
  4075. @p procedure mod_print(p:name_pointer); {print all module names in subtree |p|}
  4076. begin if p>0 then
  4077.   begin mod_print(llink[p]);@/
  4078.   out2("\")(":");@/
  4079. @.\\:@>
  4080.   tok_ptr:=1; text_ptr:=1; scrap_ptr:=0; init_stack;
  4081.   app(p+mod_flag); make_output;
  4082.   footnote(0); {|cur_xref| was set by |make_output|}
  4083.   finish_line;@/
  4084.   mod_print(rlink[p]);
  4085.   end;
  4086. @ @<Output all the module names@>=@+mod_print(root)
  4087. @* Debugging.
  4088. The \PASCAL\ debugger with which \.{WEAVE} was developed allows breakpoints
  4089. to be set, and variables can be read and changed, but procedures cannot be
  4090. executed. Therefore a `|debug_help|' procedure has been inserted in the main
  4091. loops of each phase of the program; when |ddt| and |dd| are set to appropriate
  4092. values, symbolic printouts of various tables will appear.
  4093. The idea is to set a breakpoint inside the |debug_help| routine, at the
  4094. place of `\ignorespaces|breakpoint:|\unskip' below.  Then when
  4095. |debug_help| is to be activated, set |trouble_shooting| equal to |true|.
  4096. The |debug_help| routine will prompt you for values of |ddt| and |dd|,
  4097. discontinuing this when |ddt<=0|; thus you type $2n+1$ integers, ending
  4098. with zero or a negative number. Then control either passes to the
  4099. breakpoint, allowing you to look at and/or change variables (if you typed
  4100. zero), or to exit the routine (if you typed a negative value).
  4101. Another global variable, |debug_cycle|, can be used to skip silently
  4102. past calls on |debug_help|. If you set |debug_cycle>1|, the program stops
  4103. only every |debug_cycle| times |debug_help| is called; however,
  4104. any error stop will set |debug_cycle| to zero.
  4105. @<Globals...@>=
  4106. @!debug@!trouble_shooting:boolean; {is |debug_help| wanted?}
  4107. @!ddt:integer; {operation code for the |debug_help| routine}
  4108. @!dd:integer; {operand in procedures performed by |debug_help|}
  4109. @!debug_cycle:integer; {threshold for |debug_help| stopping}
  4110. @!debug_skipped:integer; {we have skipped this many |debug_help| calls}
  4111. @!term_in:text_file; {the user's terminal as an input file}
  4112. gubed
  4113. @ The debugging routine needs to read from the user's terminal.
  4114. @^system dependencies@>
  4115. @<Set init...@>=
  4116. @!debug trouble_shooting:=true; debug_cycle:=1; debug_skipped:=0; tracing:=0;@/
  4117. trouble_shooting:=false; debug_cycle:=99999; {use these when it almost works}
  4118. reset(term_in,'TTY:','/I'); {open |term_in| as the terminal, don't do a |get|}
  4119. gubed
  4120. @ @d breakpoint=888 {place where a breakpoint is desirable}
  4121. @^system dependencies@>
  4122. @p @!debug procedure debug_help; {routine to display various things}
  4123. label breakpoint,exit;
  4124. var k:integer; {index into various arrays}
  4125. begin incr(debug_skipped);
  4126. if debug_skipped<debug_cycle then return;
  4127. debug_skipped:=0;
  4128. loop@+  begin write(term_out,'#'); update_terminal; {prompt}
  4129.   read(term_in,ddt); {read a list of integers}
  4130.   if ddt<0 then return
  4131.   else if ddt=0 then
  4132.     begin goto breakpoint;@\ {go to every label at least once}
  4133.     breakpoint: ddt:=0;@\
  4134.     end
  4135.   else  begin read(term_in,dd);
  4136.     case ddt of
  4137.     1: print_id(dd);
  4138.     2: print_text(dd);
  4139.     3: for k:=1 to dd do print(xchr[buffer[k]]);
  4140.     4: for k:=1 to dd do print(xchr[mod_text[k]]);
  4141.     5: for k:=1 to out_ptr do print(xchr[out_buf[k]]);
  4142.     6: for k:=1 to dd do
  4143.       begin print_cat(cat[k]); print(' ');
  4144.       end;
  4145.     othercases print('?')
  4146.     endcases;
  4147.     end;
  4148.   end;
  4149. exit:end;
  4150. gubed
  4151. @* The main program.
  4152. Let's put it all together now: \.{WEAVE} starts and ends here.
  4153. @^system dependencies@>
  4154. The main procedure has been split into three sub-procedures in order to
  4155. keep certain \PASCAL\ compilers from overflowing their capacity.
  4156. @^split procedures@>
  4157. @p procedure Phase_I;
  4158. begin @<Phase I:...@>;
  4159. procedure Phase_II;
  4160. begin @<Phase II:...@>;
  4161. begin initialize; {beginning of the main program}
  4162. print_ln(banner); {print a ``banner line''}
  4163. @<Store all the reserved words@>;
  4164. Phase_I; Phase_II;@/
  4165. @<Phase III:...@>;
  4166. @<Check that all changes have been read@>;
  4167. end_of_WEAVE:
  4168. stat @<Print statistics about memory usage@>;@+tats@;@/
  4169. @t\4\4@>{here files should be closed if the operating system requires it}
  4170. @<Print the job |history|@>;
  4171. @ @<Print statistics about memory usage@>=
  4172. print_nl('Memory usage statistics: ',
  4173.   name_ptr:1,' names, ', xref_ptr:1,' cross references, ',
  4174.   byte_ptr[0]:1);
  4175. for cur_bank:=1 to ww-1 do print('+',byte_ptr[cur_bank]:1);
  4176.   print(' bytes;');
  4177. print_nl('parsing required ',max_scr_ptr:1,' scraps, ',max_txt_ptr:1,
  4178.   ' texts, ',max_tok_ptr:1,' tokens, ', max_stack_ptr:1,' levels;');
  4179. print_nl('sorting required ',max_sort_ptr:1, ' levels.')
  4180. @ Some implementations may wish to pass the |history| value to the
  4181. operating system so that it can be used to govern whether or not other
  4182. programs are started. Here we simply report the history to the user.
  4183. @^system dependencies@>
  4184. @<Print the job |history|@>=
  4185. case history of
  4186. spotless: print_nl('(No errors were found.)');
  4187. harmless_message: print_nl('(Did you see the warning message above?)');
  4188. error_message: print_nl('(Pardon me, but I think I spotted something wrong.)');
  4189. fatal_message: print_nl('(That was a fatal error, my friend.)');
  4190. end {there are no other cases}
  4191. @* System-dependent changes.
  4192. This module should be replaced, if necessary, by changes to the program
  4193. that are necessary to make \.{WEAVE} work at a particular installation.
  4194. It is usually best to design your change file so that all changes to
  4195. previous modules preserve the module numbering; then everybody's version
  4196. will be consistent with the printed program. More extensive changes,
  4197. which introduce new modules, can be inserted here; then only the index
  4198. itself will get a new module number.
  4199. @^system dependencies@>
  4200. @* Index.
  4201. If you have read and understood the code for Phase III above, you know what
  4202. is in this index and how it got here. All modules in which an identifier is
  4203. used are listed with that identifier, except that reserved words are
  4204. indexed only when they appear in format definitions, and the appearances
  4205. of identifiers in module names are not indexed. Underlined entries
  4206. correspond to where the identifier was declared. Error messages, control
  4207. sequences put into the output, and a few
  4208. other things like ``recursion'' are indexed here too.
  4209.